Question

I have to check if two dates differ more than two days. As an example, 01/14/2014 and 01/15/2014 would fit the criteria because there's only one day of difference, but 01/14/2014 and 01/18/2014 would not as the latter has 4 days of difference. The dates are in string format so I've tried all sorts of data casting but couldn't succeed. So to sum up, i want to know if it is possible to create an if statement that subtract the value of two dates that are in string format and give a error if the value is bigger than 'n'. Thanks!

Was it helpful?

Solution 2

// https://gist.github.com/remino/1563878
// Converts millseconds to object with days, hours, minutes ans seconds.
function convertMS(ms) {
  var d, h, m, s;
  s = Math.floor(ms / 1000);
  m = Math.floor(s / 60);
  s = s % 60;
  h = Math.floor(m / 60);
  m = m % 60;
  d = Math.floor(h / 24);
  h = h % 24;
  return { d: d, h: h, m: m, s: s };
};

var start_date = '04/15/2014';
var end_date = '04/16/2014';

var diff = convertMS(Date.parse(end_date) - Date.parse(start_date));

if(diff.d > 1) {
  console.log('The difference is more than one day!');
}
else {
  console.log('The difference is just one day and therefore accepted!');
}

See the js fiddle: http://jsfiddle.net/E7bCF/11/
See the js fiddle with more than a day difference: http://jsfiddle.net/E7bCF/9/

OTHER TIPS

One solution would be to create a Javascript Date object (http://www.w3schools.com/js/js_obj_date.asp) for each date using simple string parsing, get the value in milliseconds using the .getTime() function and checking if this is greater than 1000 x 60 x 60 x 24 x 2 .

Try

new Date("MM/DD/YYYY") - new Date("MM/DD/YYYY")

That will return a number in milliseconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top