Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

javascript - 用JavaScript比较两个日期(Compare two dates with JavaScript)

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript?(有人可以建议一种使用JavaScript比较两个大于,小于和过去的日期的值的方法吗?)

The values will be coming from text boxes.(这些值将来自文本框。)   ask by Alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Date object will do what you want - construct one for each date, then compare them using the > , < , <= or >= .(Date对象将执行您想要的操作-为每个日期构造一个,然后使用><<=>= 。)

The == , != , === , and !== operators require you to use date.getTime() as in(==!====!==运算符要求您使用date.getTime()如)

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.(我建议您使用下拉列表或日期输入的某些类似约束形式,而不要使用文本框,以免使您陷入输入验证的困境。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...