如何在 JavaScript 中比较两个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12337752/
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
How to compare two dates in JavaScript
提问by user1657872
Possible Duplicate:
Compare dates with JavaScript
可能的重复:
使用 JavaScript 比较日期
I have two dates, start date and end date. I am comparing them like this:
我有两个日期,开始日期和结束日期。我是这样比较它们的:
var fromDate = $("#fromDate").val();
var throughDate = $("#throughDate").val();
if (startdate >= enddate) {
alert('start date cannot be greater then end date')
}
It gives the correct result... the only problem is when I compare the dates 01/01/2013 and 01/01/2014.
它给出了正确的结果......唯一的问题是当我比较日期 01/01/2013 和 01/01/2014 时。
How can I correctly compare dates in JavaScript?
如何正确比较 JavaScript 中的日期?
回答by McGarnagle
You can use this to get the comparison:
您可以使用它来进行比较:
if (new Date(startDate) > new Date(endDate))
Using new Date(str)parses the value and converts it to a Date object.
使用new Date(str)解析值并将其转换为 Date 对象。
回答by Jasper de Vries
You are comparing strings. You need to convert them to dates first. You can do so by splitting your string and constructing a new Date
您正在比较字符串。您需要先将它们转换为日期。您可以通过拆分字符串并构建新的日期来实现
new Date(year, month, day [, hour, minute, second, millisecond])
Depending on you date format it would look like
根据您的日期格式,它看起来像
var parts = "01/01/2013".split("/");
var myDate = new Date(parts[2], parts[1] - 1, parts[0]);
回答by Ramesh Kotha
var fromDate = $("#fromDate").val();
var toDate = $("#throughDate").val();
//Detailed check for valid date ranges
//if your date is like 09-09-2012
var frommonthfield = fromDate.split("-")[1];
var fromdayfield = fromDate.split("-")[0];
var fromyearfield = fromDate.split("-")[2];
var tomonthfield = toDate.split("-")[1];
var todayfield = toDate.split("-")[0];
var toyearfield = toDate.split("-")[2];
var fromDate = new Date(fromyearfield, frommonthfield-1, fromdayfield);
var toDate = new Date(toyearfield, tomonthfield-1, todayfield);
if(fromDate.getTime() > today.getTime()){
alert("from Date should be less than today")
return;
}
if(toDate.getTime() > today.getTime()){
alert("to Date should be less than today")
return;
}
if(fromDate.getTime() > toDate.getTime()){
alert("from date should be less than to date")
return;
}