乐闻世界logo
搜索文章和话题

How to compare two dates with javascript

8 个月前提问
4 个月前修改
浏览次数99

6个答案

1
2
3
4
5
6

在 JavaScript 中,可以通过多种方式来比较两个日期。以下是几种常见的方法:

1. 使用 Date 对象直接比较

JavaScript 的 Date 对象可以用来表示日期和时间。直接使用比较操作符(<, >, <=, >=)来比较两个日期对象是一种简单直接的方法:

javascript
let date1 = new Date('2023-04-01'); let date2 = new Date('2023-04-02'); if (date1 < date2) { console.log('date1 is earlier than date2'); } else if (date1 > date2) { console.log('date1 is later than date2'); } else { console.log('date1 is the same as date2'); }

2. 使用 getTime() 方法

Date 对象的 getTime() 方法返回自1970年1月1日 00:00:00 UTC以来所经过的毫秒数。这可以用于精确比较两个日期:

javascript
let date1 = new Date('2023-04-01'); let date2 = new Date('2023-04-02'); if (date1.getTime() < date2.getTime()) { console.log('date1 is earlier than date2'); } else if (date1.getTime() > date2.getTime()) { console.log('date1 is later than date2'); } else { console.log('date1 is the same as date2'); }

3. 对日期的各个组成部分分别比较

如果你想要比较日期的某个特定部分(例如,只比较年份),你可以使用 Date 对象提供的方法,如 getFullYear(), getMonth(), getDate() 等来获取相应部分的值然后进行比较:

javascript
let date1 = new Date('2023-04-01'); let date2 = new Date('2023-04-02'); if (date1.getFullYear() < date2.getFullYear()) { console.log('date1 is in an earlier year than date2'); } else if (date1.getMonth() < date2.getMonth()) { // 注意:月份从0开始,0代表一月 console.log('date1 is in an earlier month than date2'); } else if (date1.getDate() < date2.getDate()) { console.log('date1 is on an earlier day than date2'); } else { console.log('The specific parts compared are equal'); }

示例

假设你正在编写一个网站,要求用户输入他们的生日,然后你需要检查输入的日期是否是过去的日期。你可以如下实现这个功能:

javascript
function isPastDate(inputDate) { let today = new Date(); let birthDate = new Date(inputDate); // 将今天的时间部分清零 today.setHours(0, 0, 0, 0); return birthDate < today; } // 假设用户输入了 "2000-05-20" let userInput = '2000-05-20'; if (isPastDate(userInput)) { console.log('The entered date is in the past.'); } else { console.log('The entered date is not in the past.'); }

在这个例子中,isPastDate 函数用来检查用户输入的日期是否比当前日期早。如果是,函数将返回 true,表示这是一个过去的日期。在比较之前,我们通过设置时、分、秒和毫秒为0来确保只比较日期部分。

2024年6月29日 12:07 回复

Date对象将执行您想要的操作 - 为每个日期构造一个日期,然后使用><或进行比较。<=``>=

==!====和运算!==符要求您使用date.getTime()如下所示

shell
var d1 = new Date(); var d2 = new Date(d1); var same = d1.getTime() === d2.getTime(); var notSame = d1.getTime() !== d2.getTime();

需要明确的是,直接检查日期对象是否相等是行不通的

shell
var d1 = new Date(); var d2 = new Date(d1); console.log(d1 == d2); // prints false (wrong!) console.log(d1 === d2); // prints false (wrong!) console.log(d1 != d2); // prints true (wrong!) console.log(d1 !== d2); // prints true (wrong!) console.log(d1.getTime() === d2.getTime()); // prints true (correct)

不过,我建议您使用下拉菜单或某种类似的受限制的日期输入形式,而不是文本框,以免您发现自己陷入输入验证地狱。


对于好奇的人,date.getTime()文档

返回指定日期的数值,作为自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。 (之前的时间返回负值。)

2024年6月29日 12:07 回复

像往常一样比较<and ,但任何涉及or 的内容都应该使用前缀。就像这样:>``==``===``+

shell
const x = new Date('2013-05-23'); const y = new Date('2013-05-23'); // less than, greater than is fine: console.log('x < y', x < y); // false console.log('x > y', x > y); // false console.log('x <= y', x <= y); // true console.log('x >= y', x >= y); // true console.log('x === y', x === y); // false, oops! // anything involving '==' or '===' should use the '+' prefix // it will then compare the dates' millisecond values console.log('+x === +y', +x === +y); // true

运行代码片段Hide results

展开片段

2024年6月29日 12:07 回复

在 javascript 中比较日期的最简单方法是首先将其转换为 Date 对象,然后比较这些日期对象。

下面你会发现一个具有三个功能的对象:

  • 日期.比较(a,b)

    返回一个数字:

    • -1 如果 a < b
    • 0 如果 a = b
    • 1 如果 a > b
    • NaN 如果 a 或 b 是非法日期
  • 日期.inRange (d,开始,结束)

    返回布尔值或 NaN:

    • 如果_d_位于_开始_和_结束_之间(含),则为_true_
    • 如果_d_在_start_之前或_end之后,则__返回 false_。
    • NaN 如果一个或多个日期非法。
  • 日期.转换

    被其他函数用来将其输入转换为日期对象。输入可以是

    • 日期对象:输入按原样返回。
    • 数组:解释为[年、月、日] 。****注意月份是 0-11。
    • a number:解释为自 1970 年 1 月 1 日以来的毫秒数(时间戳)
    • a string:支持多种不同的格式,例如“YYYY/MM/DD”、“MM/DD/YYYY”、“Jan 31 2009”等。
    • an object:解释为具有年、月和日期属性的对象。 注意月份是 0-11。

shell
// Source: http://stackoverflow.com/questions/497790 var dates = { convert:function(d) { // Converts the date in d to a date-object. The input can be: // a date object: returned without modification // an array : Interpreted as [year,month,day]. NOTE: month is 0-11. // a number : Interpreted as number of milliseconds // since 1 Jan 1970 (a timestamp) // a string : Any format supported by the javascript engine, like // "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc. // an object : Interpreted as an object with year, month and date // attributes. **NOTE** month is 0-11. return ( d.constructor === Date ? d : d.constructor === Array ? new Date(d[0],d[1],d[2]) : d.constructor === Number ? new Date(d) : d.constructor === String ? new Date(d) : typeof d === "object" ? new Date(d.year,d.month,d.date) : NaN ); }, compare:function(a,b) { // Compare two dates (could be of any type supported by the convert // function above) and returns: // -1 : if a < b // 0 : if a = b // 1 : if a > b // NaN : if a or b is an illegal date // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(a=this.convert(a).valueOf()) && isFinite(b=this.convert(b).valueOf()) ? (a>b)-(a<b) : NaN ); }, inRange:function(d,start,end) { // Checks if date in d is between dates in start and end. // Returns a boolean or NaN: // true : if d is between start and end (inclusive) // false : if d is before start or after end // NaN : if one or more of the dates is illegal. // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(d=this.convert(d).valueOf()) && isFinite(start=this.convert(start).valueOf()) && isFinite(end=this.convert(end).valueOf()) ? start <= d && d <= end : NaN ); } }
2024年6月29日 12:07 回复

关系运算符< <= > >=可用于比较 JavaScript 日期:

shell
var d1 = new Date(2013, 0, 1); var d2 = new Date(2013, 0, 2); d1 < d2; // true d1 <= d2; // true d1 > d2; // false d1 >= d2; // false

但是,相等运算符== != === !==不能用于比较日期(的值),因为

  • 无论是严格比较还是抽象比较,两个不同的对象永远不会相等。
  • 仅当操作数引用同一对象时,比较对象的表达式才为 true。

您可以使用以下任一方法比较日期值是否相等:

shell
var d1 = new Date(2013, 0, 1); var d2 = new Date(2013, 0, 1); /* * note: d1 == d2 returns false as described above */ d1.getTime() == d2.getTime(); // true d1.valueOf() == d2.valueOf(); // true Number(d1) == Number(d2); // true +d1 == +d2; // true

Date.getTime()Date.valueOf()返回自 1970 年 1 月 1 日 00:00 UTC 以来的毫秒数。Number函数和一元运算符都在幕后+调用方法。valueOf()

2024年6月29日 12:07 回复

到目前为止,最简单的方法是将一个日期与另一个日期相减并比较结果。

shell
var oDateOne = new Date(); var oDateTwo = new Date(); console.log(oDateOne - oDateTwo === 0); console.log(oDateOne - oDateTwo < 0); console.log(oDateOne - oDateTwo > 0);

运行代码片段Hide results

展开片段

2024年6月29日 12:07 回复

你的答案