【问题标题】:Compare Date & Time in JQuery在 JQuery 中比较日期和时间
【发布时间】:2013-04-01 11:55:06
【问题描述】:

我想在 jquery 中按日期比较一些消息。 例如: 我有一个 文本框 值作为04/01/2013 13:15:32 由用户端填充。 并且 jquery 变量中的当前日期时间为04/01/2013 18:30:12 如果文本框值小于当前日期时间,则显示一条消息:

function foo(){
    usrDate = jQuery("#txtDate").val(); //getting user input date time

    currentDate = new Date(); //system current date
    currentMonth = currentDate.getMonth() + 01;
    currentDay = currentDate.getDate();
    currentYear = currentDate.getFullYear();
    currentHours = currentDate.getHours();
    currentMinutes = currentDate.getMinutes();
    currentSeconds = currentDate.getSeconds();

    currentcpDateTime = currentMonth + "/" + currentDay + "/" + currentYear + " " + currentHours + ":" + currentMinutes + ":" + currentSeconds;
       if (usrDate > currentcpDateTime ) {
       alert("you can not choose date greater then current");   
    }
   else {
      alert("valid date");
 }
}

每次都是错误的结果。 :(

【问题讨论】:

  • 当您应该比较日期对象时,您正在比较字符串。基本上你是在倒退,因为你应该将usrDate 字符串转换为日期对象,而不是将current**** 中的日期对象转换为字符串。
  • 为什么不使用纯javascript?使用gettime() 函数将日期转换为刻度,然后您可以比较两个数字。
  • 使用if(Date.parse(usrDate) > Date.parse(currentcpDateTime))
  • 您实际上可以将日期作为字符串进行比较,但如果您使用month/day/year 格式则不能。与在文件名中添加日期时相同。

标签: jquery


【解决方案1】:

为什么不使用像 jQuery UI 这样的框架,你可以像下面这样简单地做到这一点

你的 HTML

<p>Date: <input type="text" id="datepicker" /></p>
<input type="button" id="checkDate" value="CheckDate">

你的 JS

$(document).ready(function(){
    $( "#datepicker" ).datepicker();
    $('#checkDate').bind('click',function(){
        var myDAte = $('#datepicker').datepicker( "getDate" );
        var curDate = new Date();

        if(curDate>myDAte){
            alert('current date is high');
        }
        else{
            alert('selected date is high');
        }
    });
});

Live fiddle

上查看示例

【讨论】:

  • 实际上,在检查这些条件之前,我会在当前日期时间中添加几个小时。
  • 您可以add hours 到您的日期对象。所以我认为这不是问题。
【解决方案2】:

检查此处提供的解决方案可能会有所帮助,我在我的项目中使用它。您可以节省从头开始编写所有代码的时间。 http://trentrichardson.com/examples/timepicker/ .(在页尾)

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多