views:

69

answers:

3

In javascript you can create a Date object from a string, like

var mydate = new Date('2008/05/10 12:08:20');
console.log(mydate); //=> Sat May 10 2008 12:08:20 GMT+0200

Now try this using milliseconds in the string

var mydate = new Date('2008/05/10 12:08:20:551'); // or '2008/05/10 12:08:20.551'
console.log(mydate); //=> NaN

Just out of curiosity: why is this?

EDIT: thanks for your answers, which all offer sufficient explanation. Maybe in some future there will be support for use of milliseconds in date strings. Untill then I cooked up this, which may be of use to somebody:

function dateFromStringWithMilliSeconds(datestr){
    var dat = datestr.split(' ')
        ,timepart = dat[1].split(/:|\./)
        ,datestr = dat[0]+' '+timepart.slice(0,3).join(':')
        ,ms = timepart[timepart.length-1] || 0
        ,date;
    date = new Date(datestr);
    date.setMilliseconds(ms);
    return date;
}
+5  A: 

If you know the different components you can use this overload to the Date constructor:

var mydate = new Date(2008,6,10,12,8,20,551);

Note 6 for the month, as the months go from 0-11.

If needed you can take the string representation and split it to its component parts and pass those through to this constructor:

var datestring = '2008/05/10 12:08:20:551';
var datearray = datestring.split(/\s|:|\//g)
var mydate = new Date(datearray[0], parseInt(datearray[1]) + 1 , datearray[2], datearray[3],datearray[4],datearray[5],datearray[6]);

As described in this document, the string overload should conform to RFC-1123 (which in turn conforms to RFC-822) which does not support milliseconds.

Oded
May be more tricky than you think, using a datestring. If I split up the datestring (datestring.split(/\s|:|\//g)), I'll end up with an array. The Date constructor doesn't accept that. Date.apply(null,[the array]) doesn't work either, it gives the current datetime.
KooiInc
@Koolinc - then don't use the array as is and break it down to its components `[the array][0]` for the year etc.
Oded
+4  A: 

dateString

String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 1123 timestamps).

This format doesn't seem to accommodate milliseconds in the date... It may be best to just define the date without ms and then call setMilliseconds() afterwards.

J-P
That's what I do (call setMilliseconds() afterwards), just curious why a datestring couldn't contain ms. Thanks for the RFC link, I found 'hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT]' in it, so there we have it I suppose.
KooiInc
+1  A: 

The ECMA-262 standard, section 15.9.1.15, does indeed specify milliseconds in the date string format. I'm guessing the browser developers just couldn't be bothered to implement it.

Mihai