使用 Javascript 进行日期比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19537038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date Comparison Using Javascript
提问by SRJ
I have two date strings in DDMMYYYY
format. say startdate="18/02/2013"
and enddate ="26/02/2013"
.
我有两个DDMMYYYY
格式的日期字符串。说startdate="18/02/2013"
和enddate ="26/02/2013"
。
How can I compare these dates. I want enddate
to be greater than or equal to startdate
Thanks for Your Time.
我如何比较这些日期。我想enddate
大于或等于startdate
感谢您的时间。
回答by user2864740
I'm a fan of moment.jsand consider it a core part of my toolkit whenever I have to deal with dates and times - especiallywhen any form of parsing or formatting is involved.
我是moment.js的粉丝,并且在我必须处理日期和时间时将其视为我工具包的核心部分 -特别是在涉及任何形式的解析或格式化时。
You're free to do the parsing by hand and invoke the appropriate Date constructor manually, but consider the following which I consider simple and intuitive.
您可以自由地手动进行解析并手动调用适当的 Date 构造函数,但请考虑以下我认为简单直观的内容。
var startDate = moment.parse("18/02/2013", "DD/MM/YYYY");
var endDate = moment.parse("26/02/2013", "DD/MM/YYYY");
if (endDate.isAfter(startDate)) {
// was after ..
}
回答by leaf
Does this solution suits your needs (demo : http://jsfiddle.net/wared/MdA3B/)?
此解决方案是否适合您的需求(演示:http: //jsfiddle.net/wared/MdA3B/)?
var startdate = '18/02/2013';
var d1 = startdate.split('/');
d1 = new Date(d1.pop(), d1.pop() - 1, d1.pop());
var enddate = '26/02/2013';
var d2 = enddate.split('/');
d2 = new Date(d2.pop(), d2.pop() - 1, d2.pop());
if (d2 >= d1) {
// do something
}
Keep in mind that months begin with 0. MDN doc:
请记住,月份以 0 开头。MDN 文档:
month : Integer value representing the month, beginning with 0 for January to 11 for December.
month : 表示月份的整数值,从 0 开始表示一月到 11 表示十二月。
回答by LHH
var d1 = Date.parse("18/02/2013");
var d2 = Date.parse("26/02/2013");
if (d1 > d2) {
alert ("do something");
}