I am new to the lower level useful functions of JavaScript, and I find myself needing to compare two date objects, but within an hourly range. For example, if Date1 is less then two hours until (or from) Date2. How could this 开发者_JAVA百科be done?
The Date.UTC() method returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time. Get both UTC values for the dates and then subtract them. For no more than a hour difference the result should be less than 3600000(1000*60*60).
You can perform mathematical operations on Date objects, they will get converted to integers. Substracting 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
}
精彩评论