Node.js日期比较 [英] Node.js dates comparison

查看:533
本文介绍了Node.js日期比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Node.js, how do I compare the date with today's date if one of the dates is a string?

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

怎么办我比较 retdate和 mydate,以便它返回早于7天的日期?相信字符串需要修改吗?

How do I compare 'retdate' and 'mydate' so it returns date older than 7 days? I believe the string needs to be modified?

推荐答案

更新后的解决方案:

由于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/

这篇关于Node.js日期比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆