You are not logged in.
I am trying to take a string containing a date like this: "2009-12-30 12:03:45"
...and create a date object that I can use to compare to other dates.
When I create the date object the actual date gets wrong with one month. Instead of showing December 30th 2009 it shows Januari 30th 2010.
Can someone explain this behaviour?
Here is a sample code:
<html>
<head>
<script>
var string = "2009-12-30 12:03:45";
var y = string.substring(0, 4);
var m = string.substring(5, 7);
var dy = string.substring(8, 10);
var h = string.substring(11, 13);
var mi = string.substring(14, 16);
var s = string.substring(17, 19);
var myDate = new Date(y, m, dy, h, mi, s);
document.write(myDate.toString());
</script>
</head>
<body >
</body>
</html>
I get the folowing output: Sat Jan 30 2010 12:03:45 GMT+0100 (CET)
Help?
Offline
I think I figured it out.
The Date function takes months from 0-11 which means that you have to subtract 1 from the month value to get it right.
That's one hour of my life that I will never get back. Oh well...
Offline
Parse it a string and there's no need to subtract from the month.
var stringToDate = function(string) {
var regex = /(\d{4})-(\d{2})-(\d{2})\s(\d{2}:\d{2}:\d{2})/;
return new Date(string.replace(regex, "$4 $2/$3/$1"));
};
stringToDate("2009-12-30 12:03:45");
Offline