简体   繁体   English

将时间与日期进行比较

[英]Compare time with date in express

I want to compare two dates with time and i want if time difference more than one minute then expire message should display otherwise verify message should display.How can i do this here is my code 我想将两个日期与时间进行比较,如果时间差超过一分钟,则显示过期消息,否则将显示验证消息。这是我的代码

var dateFormat = require('dateformat');
var day=dateFormat(new Date(date), "yyyy-mm-dd h:MM:ss");  //2018-08-01 11:02:27
var currenttime=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss"); //2018-08-01 11:08:48

var compare = day - currenttime;
console.log(compare);

Using a JavaScript Date object you can use Date.valueOf() to get the milliseconds from the epoch of that time and then do plain subtraction to get the difference. 使用JavaScript Date对象,您可以使用Date.valueOf()从该时间的纪元获取毫秒数,然后进行简单的减法以获得差值。 If it is greater than 60000 then expire. 如果大于60000,则到期。

// I swapped your values on either side of the subtraction operator 
// to prevent a negative time difference
var compare = currentTime.valueOf() - day.valueOf()
var isExpired = compare >= 60000

console.log('isExpired', isExpired)

You can compare after generating timestamp of both time. 您可以在生成两个时间的时间戳后进行比较。 Few ways to generate timestamp 生成时间戳的几种方法

1) +new Date() 1)+新日期()

2) https://momentjs.com/ 2) https://momentjs.com/

Example using moment js : 使用moment js的示例:

var compare =  moment().format('X') - moment("1995-12-25").format('X'); // In seconds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM