JS:检查date是否less于1小时?

有没有办法检查date是否less于1小时?

像这样的东西:

<script> // old date var olddate = new Date("February 9, 2012, 12:15"); // current date var currentdate = new Date(); if (olddate >= currentdate - 1 hour) { alert("newer than 1 hour"); else { alert("older than 1 hour"); } </script> 

另外,还有一个不同的问题 – 有没有办法在一个date上添加小时?

喜欢这个:

 <script> var olddate = new Date("February 9, 2012, 12:15") + 15 HOURS; // output: February 10, 2012, 3:15 </script> 

确定

 var ONE_HOUR = 60 * 60 * 1000; /* ms */ 

那么你可以做

 ((new Date) - myDate) < ONE_HOUR 

要从约会中获得一个小时,请尝试

 new Date(myDate.getTime() + ONE_HOUR) 

那一刻图书馆真的可以帮助expression这一点。 诀窍是取date,增加时间,看现在是之前还是之后:

  lastSeenAgoLabel: function() { var d = this.lastLogin(); if (! moment(d).isValid()) return 'danger'; // danger if not a date. if (moment(d).add(10, 'minutes').isBefore(/*now*/)) return 'danger'; // danger if older than 10 mins if (moment(d).add(5, 'minutes').isBefore(/*now*/)) return 'warning'; // warning if older than 5mins return 'success'; // Looks good! }, 

使用一些ES6语法:

 const lessThanOneHourAgo = (date) => { const HOUR = 1000 * 60 * 60; let anHourAgo = Date.now() - HOUR; return date > anHourAgo; } 

使用矩量库:

 const lessThanOneHourAgo = (date) => { return moment(date).isAfter(moment().subtract(1, 'hours')); } 
 //for adding hours to a date Date.prototype.addHours= function(hrs){ this.setHours(this.getHours()+hrs); return this; } 

调用这样的函数:

 //test alert(new Date().addHours(4)); 

//试试这个://比较两个date的值:

 <Script Language=Javascript> function CompareDates() { var str1 = document.getElementById("Fromdate").value; var str2 = document.getElementById("Todate").value; var dt1 = parseInt(str1.substring(0,2),10); var mon1 = parseInt(str1.substring(3,5),10); var yr1 = parseInt(str1.substring(6,10),10); var dt2 = parseInt(str2.substring(0,2),10); var mon2 = parseInt(str2.substring(3,5),10); var yr2 = parseInt(str2.substring(6,10),10); var date1 = new Date(yr1, mon1, dt1); var date2 = new Date(yr2, mon2, dt2); if(date2 < date1) { alert("To date cannot be greater than from date"); return false; } else { alert("Submitting ..."); } } </Script> 

希望它能工作4你…