Webkit syntax analysis

Possible duplicate:
Safari JS can't parse YYYY-MM-DD date format?

I have a simple function to calculate the number of days between 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 am doing this to verify that the second date is after the first. In Firefox, this works fine, but in Webkit (Safari or Chrome) it is not. str1 and str2 are written to the console only fine, but the var var in Webkit returns NaN, and in FF it returns int.

Any idea why this could be? I am using the jQuery UI date widget to retrieve and format YYYY-MM-DD, but I don’t think this should have something to do with this.

Thanks!

+4
source share
2 answers

This little function captures Date.parse for Webkit and IE:

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

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

+1
source

The Date.parse method is inconsistent in my opinion (the actual format differs from different browsers, JS engine versions, etc.). I use the following method to perform various date operations in JavaScript (e.g. comparison):

  • Get the date components somehow (in your case, you can just split the string into "-").
  • Build the date using the components from the previous step.
  • Compare the unix timestamp of dates with the 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'); } 
+2
source

All Articles