微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript Node.js日期比较和数组按日期排序

首先,JavaScript没有像Python那样的基本日期比较吗?

在我的Node.js脚本中,我有以下几行:

console.log(Date(2012,11,10) < Date(2012,9))
console.log(Date(2012,10) > Date(2012,9))

但是,这两行都返回false.

似乎有很多关于“JavaScript中的日期比较”的问题.

然而,对于几乎所有人来说,有人用他们的自制解决方案来回应比较日期,其中一些很长和/或“hacky”.

是否真的没有固有或惯用的方式来简单比较JavaScript中的日期.
任何Node库都支持它吗?

解决方法

您需要使用new关键字
console.log(new Date(2012,10) < new Date(2012,9))
console.log(new Date(2012,10) > new Date(2012,9))

正如Elias Van Ootegem所指出的,如果省略new关键字,则返回字符串是标准:

When Date is called as a function rather than as a constructor,it returns a String representing the current time (UTC).

NOTE
The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments.

资料来源:15.9.2 The Date Constructor Called as a Function

原文地址:https://www.jb51.cc/js/154626.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐