JS: Check if date is less than 1 hour ago?

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

Is there a way to check if a date is less than 1 hour ago?

Something like this:

 

Also, different question - is there a way to add hours to a date?

Like this:

 

回答1:

Define

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

then you can do

((new Date) - myDate) < ONE_HOUR

To get one hour from a date, try

new Date(myDate.getTime() + ONE_HOUR)                       


回答2:

Using some ES6 syntax:

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

Using the Moment library:

const lessThanOneHourAgo = (date) => {     return moment(date).isAfter(moment().subtract(1, 'hours')); }


回答3:

the moment library can really help express this. The trick is to take the date, add time, and see if it's before or after now:

  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!   },


回答4:

//for adding hours to a date Date.prototype.addHours= function(hrs){     this.setHours(this.getHours()+hrs);     return this; }

Call function like this:

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


回答5:

//try this: // to compare two date's:

 

Hope it will work 4 u...



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!