4

Possible Duplicate:
Safari JS cannot parse YYYY-MM-DD date format?

I have a simple function to calculate the amount 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!

1

2 Answers 2

2

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'); } 
Sign up to request clarification or add additional context in comments.

2 Comments

You need to subtract 1 on the month part, when calling the Date constructor, not to add (months are zero-based). Also to compare the timestamps, you don't need to explicitly call the getTime method, by comparing if (d1 < d2) the < operator will implicitly convert the two objects involved to primitive.
Thank you for your comments, Christian.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.