You are not logged in.

#1 2009-12-30 17:24:18

antis
Member
From: sweden
Registered: 2007-05-18
Posts: 108

Javascript help with weird date output.

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

#2 2009-12-30 17:50:14

antis
Member
From: sweden
Registered: 2007-05-18
Posts: 108

Re: Javascript help with weird date output.

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... smile

Offline

#3 2009-12-31 00:05:21

N30N
Member
Registered: 2007-04-08
Posts: 273

Re: Javascript help with weird date output.

Parse it a string and there's no need to subtract from the month. wink

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

Board footer

Powered by FluxBB