Node.js日期比较

时间:2016-09-16 02:32:00

标签: node.js date

在Node.js中,如果其中一个日期是字符串,如何将日期与今天的日期进行比较?

var retdate = new Date();
retdate.setDate(retdate.getDate()-7);
var mydate = '2016-07-26T09:29:05.000Z'

如何比较'retdate'和'mydate',以便它返回超过7天的日期?我相信字符串需要修改?

3 个答案:

答案 0 :(得分:5)

更新解决方案:

由于OP要求提供基于标准Javascript API的解决方案。

您可以做的是,由于日期字符串符合ISO-8601日期格式,您可以通过将日期字符串传递给构造函数来创建Date对象。

获得2个Date个对象后,您可以直接从提供epoch日期时间的对象中减去。因此,使用它,您只需要将它除以一周(7天)内的总毫秒数,以确定日期A是否早于日期B.

示例:

var retdate = new Date();
retdate.setDate(retdate.getDate()-7);
var mydatestring = '2016-07-26T09:29:05.00';
var mydate = new Date(mydatestring);

var difference = retdate - mydate; // difference in milliseconds

const TOTAL_MILLISECONDS_IN_A_WEEK = 1000 * 60 * 24 * 7;

if (Math.floor(difference / TOTAL_MILLISECONDS_IN_A_WEEK) >= 7) {
    console.log("Current date is more than 7 days older than : " + mydatestring);
}

MomentJS解决方案:

与'Newbee Dev'一样,MomentJS是一个很好的JS日期时间模块,用于解决各种与日期相关的问题。

首先使用moment(...)构造函数解析日期时间字符串,然后使用diff(...,'days') API进行日期比较。

示例:

var datetime = '2016-07-26T09:29:05.000Z';
var localTime = moment();
var otherTime = moment(datetime);

console.log("Current datetime is older than " + datetime + " by 7 days = " + (localTime.diff(otherTime, 'days') >= 7));
<script src="http://momentjs.com/downloads/moment.js"></script>

查看http://momentjs.com/

答案 1 :(得分:1)

使用时刻js只需将此模块添加到依赖项中

var moment = require('moment');

retdate = moment(retdate).format('YYYY-MM-DD');
mydate = moment(mydate).format('YYYY-MM-DD');

答案 2 :(得分:1)

您可以将日期转换为毫秒并进行数学运算并将其转换回标准日期。

//Today's date
const today = new Date()
  //Six days before today
const sixDaysAgo = new Date(+(new Date()) - 6 * 24 * 60 * 60 * 1000)
  //Seven days before today
const sevenDaysAgo = new Date(+(new Date()) - 7 * 24 * 60 * 60 * 1000)
  //One year ago
const oneYearAgo = new Date(+(new Date()) - 365 * 24 * 60 * 60 * 1000)
  //Given date from a date string
const givenDate = new Date("2016-07-26T09:29:05.000Z")

//Convert the range of days to milliseconds
//(This wont work if the date very old)
const sevenDaysInMiliSec = 7 * 24 * 60 * 60 * 1000

var dateToValidate = sevenDaysAgo;

if (today - dateToValidate >= sevenDaysInMiliSec) {
  console.log(dateToValidate + " is seven days older or more")
} else {
  console.log(dateToValidate + " is less than seven days old")
}

dateToValidate = sixDaysAgo;

if (today - dateToValidate >= sevenDaysInMiliSec) {
  console.log(dateToValidate + " is seven days older or more")
} else {
  console.log(dateToValidate + " is less than seven days old")
}

dateToValidate = oneYearAgo;

if (today - dateToValidate >= sevenDaysInMiliSec) {
  console.log(dateToValidate + " is seven days older or more")
} else {
  console.log(dateToValidate + " is less than seven days old")
}

dateToValidate = givenDate;

if (today - dateToValidate >= sevenDaysInMiliSec) {
  console.log(dateToValidate + " is seven days older or more")
} else {
  console.log(dateToValidate + " is less than seven days old")
}