检查日期是否少于1小时前?

有没有办法像这样检查一次约会是否在不到一小时之前?

// 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");
}

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

var olddate = new Date("February 9, 2012, 12:15") + 15 HOURS; // output: February 10, 2012, 3:15
121883 次浏览

定义一下

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

然后你就可以

((new Date) - myDate) < ONE_HOUR

从约会中抽出一个小时,试试看

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

调用函数如下:

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

//试试这个: //比较两个日期:

<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>

希望它能起作用。

moment library可以真正帮助表达这一点。诀窍是记下日期,加上时间,看看是在现在之前还是之后:

  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;
const anHourAgo = Date.now() - HOUR;


return date > anHourAgo;
}

使用 等一下库:

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

使用 Moment的速记语法:

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

在这种情况下使用 moment 会容易得多,你可以试试这个:

    let hours = moment().diff(moment(yourDateString), 'hours');

它会给你整数值,比如1,2,5,0等等,所以你可以很容易的使用条件检查,比如:

if(hours < 1) {

此外,还有一件事,你可以得到更准确的结果的时间差(小数,如1.2,1.5,0.7等)得到这种结果使用这种语法:

let hours = moment().diff(moment(yourDateString), 'hours', true);

如果你有任何进一步的问题,请告诉我

你可以这样做:

  1. 首先找出以毫秒为单位的两个日期 i-e 的差
  2. 将毫秒转换为分钟
  3. If minutes are less than 60, then it means date is within hour else not within hour.
var date = new Date("2020-07-12 11:30:10");
var now = new Date();
var diffInMS = now - date;
var msInHour = Math.floor(diffInMS/1000/60);
if (msInHour < 60) {
console.log('Within hour');
} else {
console.log('Not within the hour');
}