用 JavaScript 比较两个日期 [英] Compare two dates with JavaScript

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

问题描述

有人可以建议一种使用 JavaScript 比较两个日期大于、小于和不过去的值的方法吗?值将来自文本框.

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.

推荐答案

Date 对象 会做你想做的 - 为每个日期构造一个,然后使用 >, <, 比较它们><=>=.

The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.

==!====!== 运算符要求您使用 date.getTime() 就像在

The ==, !=, ===, and !== operators require you to use date.getTime() as in

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

要清楚,直接检查日期对象是否相等是行不通的

to be clear just checking for equality directly with the date objects won't work

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)

不过,我建议您使用下拉菜单或类似的日期输入限制形式,而不是文本框,以免您陷入输入验证的困境.

I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.

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

For the curious, date.getTime() documentation:

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

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

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

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