如何在JavaScript中比较两个日期

时间:2012-09-09 08:52:56

标签: javascript

  

可能重复:
  Compare dates with JavaScript

我有两个日期,开始日期和结束日期。我正在比较它们:

var fromDate = $("#fromDate").val();
var throughDate = $("#throughDate").val();

if (startdate >= enddate) {
    alert('start date cannot be greater then end date')
}

它给出了正确的结果......唯一的问题是我比较日期01/01/2013和01/01/2014。

如何正确比较JavaScript中的日期?

3 个答案:

答案 0 :(得分:7)

您可以使用它来进行比较:

if (new Date(startDate) > new Date(endDate)) 

使用new Date(str)解析值并将其转换为Date对象。

答案 1 :(得分:3)

您正在比较字符串。您需要先将它们转换为日期。您可以通过拆分字符串并构建new Date

来实现
new Date(year, month, day [, hour, minute, second, millisecond])

根据您的日期格式,它看起来像

var parts = "01/01/2013".split("/");
var myDate = new Date(parts[2], parts[1] - 1, parts[0]);

答案 2 :(得分:0)

        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;
    }