使用JavaScript比较两个日期 [英] Compare two dates with 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 code>
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 data 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.
这篇关于使用JavaScript比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!