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!
            Asked
            
        
        
            Active
            
        
            Viewed 72 times
        
    0
            
            
        - 
                    1http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript/15289883#15289883 – JohanVdR Mar 30 '14 at 16:28
- 
                    You really couldn't figure this out ? -> `if ( (new Date('01/14/2015').getTime() - new Date('01/15/2014').getTime()) > (1000*60*60*24*2) )` – adeneo Mar 30 '14 at 16:30
- 
                    http://jsfiddle.net/adeneo/63ftd/ – adeneo Mar 30 '14 at 16:33
3 Answers
1
            
            
        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 .
 
    
    
        numX
        
- 830
- 7
- 24
0
            
            
        Try
new Date("MM/DD/YYYY") - new Date("MM/DD/YYYY")
That will return a number in milliseconds.
 
    
    
        itdoesntwork
        
- 4,666
- 3
- 25
- 38
0
            // 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/
 
    
    
        JohanVdR
        
- 2,880
- 1
- 15
- 16
