开发者

JavaScript Date getTime() inconsistent

I'm trying to implement a parser for the tablesorter plugin for jQuery and I have this strange behaviour with the getTime() value for dates. The following code:

var dateOne = '03/04/2010';
var dateTwo = '28/10/2008';
var dateOneTime = new Date(dateOne).getTime();
var dateTwoTime = new Date(dateTwo).getTime();
var diff = dateOneTime - dateTwoTime;

alert('dateOneTime: ' + dateOne开发者_运维技巧Time + '\ndateOne: ' + dateOne + '\nDateTwoTime: ' + dateTwoTime + '\ndateTwo : ' + dateTwo + '\none - two: ' + diff);

Gives a getTime() result for the 2010 date as 1267 billion or so, and for the 2008 date 1271 billion. Therefore subtracting dateTwo from dateOne gives a negative number. Why is this? Surely the dateTwo value, being in 2008, should be smaller?


Date expects MM/DD/YYYY

You are passing in DD/MM/YYYY


By default, the format is mm/dd/yyyy. Thus, 28/10/2008 is being interpreted as 04/10/2010.


When you initialize a date in JS via a string, it should be an RFC1123-compliant format - yours aren't.


new Date(dateTwo) is being interpreted incorrectly as April 10 2010 because the Date constructor is expecting MM/DD/YYYY instead of the DD/MM/YYYY you are passing.

try

var dateOne = '04/03/2010';
var dateTwo = '10/28/2008';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜