【问题标题】:How to compare the date part alone from a date time value如何从日期时间值单独比较日期部分
【发布时间】:2013-11-25 08:57:45
【问题描述】:

我有两个变量,即

date1 = Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
date2 = Mon Nov 25 2013 14:13:55 GMT+0530 (IST)

当我比较两个日期时,我发现date2 更大,我需要的是正确的。但我不想检查我拥有的两个日期的时间部分。如何从这两个日期中单独获取日期部分并进行比较?

var today = new Date();     //Mon Nov 25 2013 14:13:55 GMT+0530 (IST) 
d = new Date(my_value);     //Mon Nov 25 2013 00:00:00 GMT+0530 (IST) 
if(d>=today){               //I need to check the date parts alone.
    alert(d is greater than or equal to current date);
}

【问题讨论】:

标签: javascript jquery


【解决方案1】:

尝试使用Date.setHours清除时间:

dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])

示例代码

var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value); 
d.setHours(0, 0, 0, 0);

if(d >= today){ 
    alert(d is greater than or equal to current date);
}

【讨论】:

【解决方案2】:

最好的方法是修改接受答案的if 声明如下

if(d.setHours(0,0,0,0) >= today.setHours(0,0,0,0))

通过这种方式,您也可以轻松检查是否相等,因为setHours() 的返回类型是整数。

【讨论】:

    【解决方案3】:
         var StartDate = $("#StartDate").val();
    
          var EndDate = $("#EndDate").val();
    
          if ((( EndDate - StartDate)/ (86400000*7))<0) 
          { 
           alert("Start Date Must Be Earlier Than End Date"); $("#StartDate").focus(); 
            error = true; 
            return false; 
          }
    

    【讨论】:

    • 欢迎来到 SO!请意识到这个问题已有 2 年多的历史了……当然,您仍然可以回答,尤其是当技术不断发展,新工具/语言可用时,这为更好的解决方案打开了空间。在这种情况下,请解释为什么您认为您的解决方案比之前提出的解决方案更好。
    【解决方案4】:

    试试:

        var today = new Date();     //Mon Nov 25 2013 14:13:55 GMT+0530 (IST) 
        var d = new Date(my_value);     //Mon Nov 25 2013 00:00:00 GMT+0530 (IST) 
        var todayDateOnly = new Date(today.getFullYear(),today.getMonth(),today.getDate()); //This will write a Date with time set to 00:00:00 so you kind of have date only
        var dDateOnly = new Date(d.getFullYear(),d.getMonth(),d.getDate());
    
        if(dDateOnly>=todayDateOnly){               
            alert(d is greater than or equal to current date);
        }
    

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 2012-05-08
      • 2019-03-26
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 2016-09-19
      • 2022-01-02
      相关资源
      最近更新 更多