开发者

Webkit date parsing [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Safari JS cannot parse YYYY-MM-DD date format?

I have a simple function to calculate the a开发者_开发技巧mount of days between to dates.

function checkDias(){
    str1 = $('#salida').val();
    str2 = $('#regreso').val();
    difference = Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000);
    if (diferencia > 0) { } else {
        console.log(difference); console.log(str1); console.log(str2);
       // alert the user....
    }
}

I do this to check that the 2nd date is after the first one. In Firefox this works ok but in Webkit (Safari or Chrome) it doesn't. str1 and str2 log into the console just fine but the difference var in Webkit return NaN and in FF it returns the int value.

Any idea why this might be? I'm using a jQuery UI date widget to get and YYYY-MM-DD format but I don't think this has to do anything with it.

Thanks!


The Date.parse method is inconsistent in my opinion (the actual format differs across various browsers, versions of JS engine etc.). I'm used to the following method to make various operations on dates in JavaScript (compare for example):

  1. Get the components of the date somehow (in your case you can just split the string by '-').
  2. Construct the date using components from the previous step.
  3. Compare the unix timstamp of the dates using getTime() method.

Here is the code:

var d1Parts = s1.split('-'),
    d2Parts = s2.split('-'),
    d1 = new Date(d1Parts[0], d1Parts[1]-1, d1Parts[2]),
    d2 = new Date(d2Parts[0], d2Parts[1]-1, d2Parts[2]);

if ( d1.getTime() < d2.getTime() ) {
    console.log('the first date is before the second');
}


This small function fixes Date.parse for Webkit and IE:

https://github.com/csnover/js-iso8601

I tested it and now Webkit and IE parse the dates as expected.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜