且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Node.js日期比较

更新时间:2023-11-29 11:31:52

更新后的解决方案:

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

Since OP is asking for a solution that is based on standard Javascript API.

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

What you could do is, since your date string is compliance to the ISO-8601 date format, you can create the Date object through passing the date string to the constructor.

一旦获得2个 Date 对象,您就可以直接从对象中减去给定时期日期时间的对象。因此,使用该值,您只需要用一周(7天)的毫秒总数除以得出日期A是否早于日期B。

Once you got 2 Date objects you can directly subtract from objects giving you the epoch datetime. So using that, you just need to dividend it by the total number of milliseconds in a week (7 days) to figure out whether Date A is older than Date B or not.

示例:

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日期时间模块。

Like 'Newbee Dev' said MomentJS is a good JS datetime module for solving all kinds of date related problems.

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

First parse your datetime string using the moment(...) constructor then use the diff(...,'days') API to do the day comparison.

示例:

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/