Skip to content

Instantly share code, notes, and snippets.

@paulbjensen
Created January 7, 2011 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulbjensen/769816 to your computer and use it in GitHub Desktop.
Save paulbjensen/769816 to your computer and use it in GitHub Desktop.
Trying to setup a new Date() object is a pain in the ass!
// Stupid JavaScript Date inconsistency
//So, Say you have a string Date
var lastDayOf2010 = "2010-12-31";
var choppedLastDayOf2010 = lastDayOf2010.split('-');
// Let's say you decide to parse the date like so:
var badDate = new Date(
choppedLastDayOf2010[0],
choppedLastDayOf2010[1],
choppedLastDayOf2010[2]
);
//> Mon Jan 31 2011 00:00:00 GMT+0000 (GMT)
// wtf?
//
// Turns out that to pass a month into the new Date()
// argument, you have to pass in a number between 0
// (for January) and 11 (for December).
//
// So, to get the correct date, I have to do this:
//
//
var correctDate = new Date(
choppedLastDayOf2010[0],
choppedLastDayOf2010[1] - 1,
choppedLastDayOf2010[2]
);
//> Fri Dec 31 2010 00:00:00 GMT+0000 (GMT)
// So you would imagine the same rule would apply to
// the day (with 0 being the first day of a month),
// but it doesn't:
var wtfDate = new Date(
choppedLastDayOf2010[0],
choppedLastDayOf2010[1] - 1,
0
);
//> Tue Nov 30 2010 00:00:00 GMT+0000 (GMT)
// It seems inconsistent, and is a pain in the ass!
// Alternatively, you can use the Date.parse() method to
// convert the lastDayOf2010 string variable into a number
// representing unix epoch time, and then pass the number
// into the new Date() code:
var goodDate = new Date(Date.parse(lastDayOf2010));
// 2011. Paul Jensen
@olivernn
Copy link

olivernn commented Jan 8, 2011

I think the month is from 0 to 11 so you could have the month names in an array and do monthNames[date.getMonth()].

It is still very weird though!

@paulbjensen
Copy link
Author

Agreed, oh well, at least there's Date.parse().

Hope all is going well over in Clerkenwell.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment