JS日期比较如何工作? [英] How does JS date comparison work?

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

问题描述

让我们假设我有一个从字符串构造的适当的 Date 对象:Tue Jan 12 21:33:28 +0000 2010 code>。

Let's assume I have a proper Date object constructed from the string: "Tue Jan 12 21:33:28 +0000 2010".

var dateString = "Tue Jan 12 21:33:28 +0000 2010";
var twitterDate = new Date(dateString);

然后我使用< code>> 小于大于比较运算符,以查看其是否比类似构造的更新或更新< $ c> Date 。是用于使用指定的运算符比较日期的算法,还是特定未指定的运算符,如 localeCompare ?换句话说,我保证以这种方式获得更近的日期?

Then I use the < and > less than and greater than comparison operators to see if it's more or less recent than a similarly constructed Date. Is the algorithm for comparing dates using those operators specified, or is it specifically unspecified, like localeCompare? In other words, am I guaranteed to get a more recent date, this way?

var now = new Date();
if (now < twitterDate) {
    // the date is in the future
}


推荐答案

关于ECMAScript中对象的关系操作依赖于内部 ToPrimitive 函数(带提示号),在定义时,使用 valueOf

Relational operations on objects in ECMAScript rely on the internal ToPrimitive function (with hint number) that you can access, when it is defined, using valueOf.

尝试

var val = new Date().valueOf();

你会得到日期的内部值,就像许多语言一样,自从1970年1月1日午夜12点以来的毫秒数(与使用 getTime())相同。

You'll get the internal value of the date which is, as in many languages, the number of milliseconds since midnight Jan 1, 1970 UTC (the same that you would get using getTime()).

意味着您在设计上始终确保日期比较正确工作。

This means that you're, by design, ensured to always have the date comparison correctly working.

本文将为您详细介绍 toPrimitive 相对于比较)。

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

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