Making a basic date(technical) - javascript

NO JQUERY! I have a drop down in which the user selects a day month and year. I create the following code and pass these values into the variable using setFullYear. At times I also add days to this variable which is waht the variable ev_num is for. When I write this to the page it displays a lot of unnecessary info...
Sat Jan 01 2011 11:44:26 GMT-0500 (Eastern Standard Time)
I want it to simply read 'Jan 01 2011' or something like that. Does anyone know how I would fix this. Here is a jsfiddle of the entire page... http://jsfiddle.net/fET6v/
var myDate=new Date();
var ev_num = parseInt(document.getElementById("leave").value)
myDate.setFullYear(sel_year.value,sel_month.value,sel_day.value);
var event_value = document.getElementById("leave").value;

var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
document.write(currentMonth + " " + day + " " + year);
This will print today's date with abbreviated months. It's fully customizable.
http://jsfiddle.net/iansan5653/u7hkE/
EDIT: See this demo for the leading zero in front of the day number: http://jsfiddle.net/iansan5653/u7hkE/1/

If you don't want the time and timezone to appear, use the .toDateString method instead of the simple toString. If you want a custom format, you will need to build the string yourself, you can get the single year/month/date values with the respective methods from your Date object. There are some (googlable) libraries to do that, a single method for your case would be
function myDateString(date) {
return ["Jan","Feb","Mar", …][date.getMonth()] +
" "+("0"+date.getDate()).substr(-2) +
" "+date.getFullYear();
}

http://blog.stevenlevithan.com/archives/date-time-format

Related

Format the following date into YYYY-mm-dd in JS

How would I go about converting following date:
Thu Feb 18 12:25:00 SGT 2016
into a format like '2016-02-18'?
I know,
That, using a new Date(Date.parse('...')), with calls, will help me get it. But the problem being timezone part (SGT).
I dont want to use any libraries out there.
What would be the effective way to go about this?
Any help is appreciated!
PS:
Ok, I have tried
new Date(Date.parse('Thu Feb 18 12:25:00 SGT 2016'))
but of-course, it is going to me 'invalid date' error.
I guess I should wait for you to post some code, but here's an example. It splits the string into parts, converts the month name to a number, then outputs the bits you want in the order you want. The slice on the month name is just in case you want to use the full month name, but maybe that's unnecessary:
function reformatDate(s){
var b = s.split(/[\s:]/);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
return b[7] + '/' + months[b[1].toLowerCase().slice(0,3)] + '/' + ('0'+b[2]).slice(-2);
}
document.write(reformatDate('Thu Feb 18 12:25:00 SGT 2016'));
That format date string (y/m/d) isn't consistent with any standard that I know of and likely will not be parsed by most browsers.
Why not just take the individual components of the date object and build a string from them?
full_date = new Date();
formatted_date_string = full_date.getFullYear() + "-" + (full_date.getMonth()+1) + "-" + full_date.getDate();
I'll leave it to you to sort out the leading 0s on the day and month.
var input="Thu Feb 18 12:25:00 SGT 2016";
var ar=input.split(" ");
var months = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"};
console.log(ar[ar.length-1]+"-"+months[ar[1]]+"-"+ar[2]);
Try this code no date parsing required. Please check on console for result.
var date = "Thu Feb 18 12:25:00 SGT 2016";
date = date.replace("SGT","GMT+0800") // replaces SGT with GMT+0800 because
singapore time is 8 hrs ahead than GMT timezone
var newdate = new Date(Date.parse(date))
var requiredDate = newdate.toLocaleDateString()

Parse & format javascript date: dd M YYYY to YYYY-mm-dd

I have a date which looks like:
30 Apr 2015
How do I parse and display the date like this (without Moment.js)?
2015-04-31 (or YYYY-mm-dd)
The easiest thing to do might be to use moment.js.
If you prefer rolling your own solution in vanilla JS, this will work:
var padZero = function (integer) {
return integer < 10 ? '0' + integer : '' + integer
};
var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' +
(padZero(myDate.getMonth()+1)) + '-' +
(padZero(myDate.getDate()));
console.log(myDateString); // 2015-04-30
The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :)
var x = new Date("30 Apr 2015");
Formatting the date is a little trickier. You have a few options. Date natively supports several output methods (.toDateString(), .toLocaleDateString(), etc) but none of them match the format you've given. It does, however, allow you to individually select the day, month and year values for the date. So, you can assemble them manually:
console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())
Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate()).
However, your better choice is to take a look at moment.js, which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists.
Use moment.js
Convert your date like this:
var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30
DEMO
you can do that easy with
//define Date
var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
var months = {
Jan:'01',
Feb:'02',
Mar:'03',
Apr:'04',
May:'05'
};
// split our Date and rearrange as yyyy-mm-dd
var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
alert(reform);// return 2015-04-31

javascript get current datetime

Good evening,
I am writing server application that will be running on node websocket and im having hard time processing dates.
This is piece of code that i wrote:
var getDatetime = function() {
var checkLength = function(part) {
return (part < 10) ? '0' + part : part;
};
var date = new Date(),
year = date.getFullYear(),
month = checkLength(date.getMonth()),
day = checkLength(date.getDay()),
hour = checkLength(date.getHours()),
minute = checkLength(date.getMinutes()),
second = checkLength(date.getSeconds());
return day + '-' + month + '-' + year + ' ' + hour + ':' + minute + ':' + second;
};
It pains me to use it like that, im no pro with js so im asking, is there a method like in php date('d-m-Y H:i:s', time()) with which you can get current datetime in nice and clean way instead of doing this the way i showed?
I would recommend Moment.js. It can be deployed both on front end and nodejs server. Here's the install instruction for nodejs.
With the Javascript constructor, date(), under the Conversion getter section of the page linked to, there are several options for converting the format such as date.doDateString(). This will create a human-readable string, and with it being a string it can be cut up and re-arranged as needed with the use of sub strings.
var a = new Date();
console.log(a); // Wed March 25th 2015 16:10:38GMT -0700 (Pacific Daylight Time)
With AngularJS you have an easy way to show dates which are in the epoch function, with the date filter.

Converting a date in an invalid javascript format to an ics standard datetime field

The date and time are actually separate in the data I have however I thought combining them would be the ideal solution?
The unaltered data looks like the following:
2014/09/04 and 02:30PM
var aDate = new Date('2014/09/04 02:30PM');
//Invalid date....
console.log(aDate.toString());
Needs to convert to the date that .ics files use which looks like:
20140904T023000 --> This is what the above date would turn into.
How do I do this?
JSBin you could test in...
Change
var aDate = new Date('2014/09/04 02:30PM');
to
var aDate = new Date('2014/09/04 02:30 pm');
and it should work. You just need to put in a SPACE before PM. This will not give you invalid date error. Then you can use that date to get ICS format.
Here is the logic to get ICS format. I know this is not as efficient, but tried to keep it simple.
var pre =
aDate.getFullYear().toString() +
((aDate.getMonth() + 1)<10? "0" + (aDate.getMonth() + 1).toString():(aDate.getMonth() + 1).toString()) +
((aDate.getDate() + 1)<10? "0" + aDate.getDate().toString():aDate.getDate().toString());
var post = (aDate.getHours()%12).toString() + aDate.getMinutes().toString() + "00";
console.log(pre + "T" + post);
You should be able to parse the date fine if you use 24 hour notation for time rather than denoting AM/PM.
From Chrome console:
(new Date('2014/09/04 02:30PM'));
Invalid Date
(new Date('2014/09/04 14:30'));
Thu Sep 04 2014 14:30:00 GMT+0100 (BST)
With this object, you should be able to construct the ICS format compliant date you require using the various getters on the Date prototype.
There are no default api`s to convert to .ics file format, you can however do it manually.
function toITCFormat(date, time)
{
var timeCont = [],
dateCont = [];
if(time.toLowerCase().indexOf('pm')!=-1)
{
timeCont = time.toLowerCase().replace('pm',00).split(':'); //assuming from your question seconds is never mentioned but only hh:mm i.e. hours and minutes
timeCont[0] = (parseInt(timeCont[0])+12)%24;
}
else
{
timeCont = time.toLowerCase().replace('am',00).split(':');
}
dateCont = date.split('/');
return dateCont.join('')+'T'+timeCont.join('');
}
var x = toITCFormat('2014/09/04','02:30PM');
console.log(x);// this will output ur .ics format
JSFiddle Example

Simple Javascript date conversion

I have this - Tue, 03 Apr 2012 05:00:33 GMT
Need this - 20120323111106
Google has failed me, I think I just don't know exactly what im searching for so I kept it simple here with the question.
EDIT: The dates do not match obviously, just looking to get it in that format.
Good answer (later edited):
I think this is what you are looking for :
function addZero(val){
if (parseInt(val) < 10) return "0" + val;
return val;
}
var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT");
console.log(dt.getFullYear() + addZero(dt.getMonth()) + addZero(dt.getDay()) + addZero(dt.getHours()) + addZero(dt.getMinutes()) + addZero(dt.getSeconds()))
Initial wrong answer :
var dt = new Date("Tue, 03 Apr 2012 05:00:33 GMT")
var miliseconds = dt.getTime();
I've tested it and my computer converted it automatically to GMT +3 (my timezone), you can play with that according to your timezone.
Writing a function to parse a string should work for you. By the looks of it, any date string that you currently have will be the same length. If this is the case this should be relatively easy. Just make sure your strings are in this format before you pass them in as arguments.
function parse(string) {
var out = "yyyymmddhhmmss"
out.charAt(0) = string.charAt(13);
out.charAt(1) = string.charAt(14);
out.charAt(2) = string.charAt(15);
out.charAt(3) = string.charAt(16);
//if else statements for each month converting to numbers
if (string.substring(9,12).equals("Apr")) {
out.charAt(4) = '0';
out.charAt(5) = '4';
}
out.charAt(6) = string.charAt(18);
out.charAt(7) = string.charAt(19);
...etc for the remaining values
return out
}
My numbers for character indices may be off, but if you use this idea, it should set you straight. Define a function and pass in the dates in the format you have, and out will come the dates in the format you want.

Categories

Resources