Why can't I create a Date from a string including milliseconds?
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;
}
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.
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.
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.
精彩评论