JavaScript Date Comparison

I am new to cheaper JavaScript functions and I need to compare two date objects, but within the hour range. For example, if Date1 is less than two hours before (or from) Date2. How can I do that?

+2


a source to share


2 answers


The Date.UTC () method returns the number of milliseconds in a date string since midnight January 1, 1970, according to UTC. Get both UTC values ​​for dates, then subtract them. The result must be less than 3600000 (1000 * 60 * 60) by no more than one hour difference.



+1


a source


You can perform mathematical operations on Date objects, they are converted to integers. Highlighting two date objects will give you the difference in milliseconds. Two hours = 120 minutes = 7200 seconds = 7200000 milliseconds.



var d1 = new Date('5/13/2010 08:30');
var d2 = new Date('5/13/2010 10:00');

if( d2 - d1  < 7200000 ){
//less than two hours difference
}

      

0


a source







All Articles