【问题标题】:how to compare two different date in jquery如何在jquery中比较两个不同的日期
【发布时间】:2017-06-01 08:20:04
【问题描述】:

var date = $("#date").text();
// this date  is variable 01/06/2017


// this  date is also  will be variable
var startdate = 01 / 06 / 2017
if (date == startdate) {}
if (date < startdate) {}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"&gt;&lt;/script&gt;

如何比较两个日期并检查我得到的不同条件

【问题讨论】:

  • 你想要什么?
  • var date =Date.parse(_dateTimeHelper.formatLocalDate($("#date").text())); startdate = Date.parse(_dateTimeHelper.formatLocalDate(startdate));我试试这个,但我得到的日期是 2017 年 5 月 31 日,开始日期是 2017 年 6 月 1 日,如果我申请,如果日期显示更大,我应该显示 startdate 更大
  • 如果您需要操作日期。我建议你使用moment.js
  • 这可能也有帮助How to compare date/time strings

标签: jquery html


【解决方案1】:

您需要将两个 var 都声明为 Date,现在您只是在比较字符串与字符串,这里我做了一个示例:https://cg6.tutorialspoint.com/share/661/IytBM5oT

$(document).ready(function(){

$("button").click(function(){

    var date = new Date($("#date").val());

    var startdate = new Date("11/01/2014");

    if(date < startdate)
    {
     $("#datevalueresault").text("startdate is SMALLER than input");
    }
    if(date > startdate)
    {
       $("#datevalueresault").text("startdate is BIGGER than input"); 
    }
    if(date.getTime() === startdate.getTime())
    {
       $("#datevalueresault").text("both date are the SAME"); 
    }
});

});

【讨论】:

  • 那么您需要检查您从 #date 获得的值!它需要采用“日期”可以读取的格式,例如:“11/01/2014”。
  • 我已经更改了答案,只需将我的代码复制到您的脚本中,并确保输入名为“date”,并创建名为“datevalueresault”的文本,然后您将在那里看到比较结果,我还为您创建了一个示例:cg6.tutorialspoint.com/share/661/IytBM5oT
【解决方案2】:

也许这就是你要找的。​​p>

我正在使用Date.parse()

var date = Date.parse( $("#date").text() )
var startdate = Date.parse( $("#startdate").text() )

if (date == startdate) {
  $('#comparison').text('same day')
}
if (date < startdate) {
  $('#comparison').text('previous day')
}
if (date > startdate) {
  $('#comparison').text('next day')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>


<p>What is <span id="date">31 may 2017</span> compared to <span id="startdate">1 jun 2017 </span></p>
<p id="comparison"></p>

【讨论】:

  • mr.a.barbieri 我已经提到如果 2017 年 5 月 31 日和 2017 年 6 月 1 日如果使用这是条件,如果(2017 年 5 月 31 日
  • 我用你的日期更新了代码,但我不明白你的意思。我觉得不错……
  • 如果我们使用 Date.parse 这将在 may31 大于 6 月 1 日时使用
  • 很难理解你想说什么。
  • ...从您发表的其他评论中我可能已经理解了。您需要将日期作为stringDate.parse() 内传递,否则您只是在比较字符串,而不是日期。在我的示例中,我将span 中的字符串传递给Date.parse() ussign jQuery。不过,您可以按照自己的方式进行操作。
【解决方案3】:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
 var date =new Date($("#date").text());
 // this date  is variable 01/06/2017


 // this  date is also  will be variable
 var startdate= new Date(2017,5,1)//5 is for sixth month
 if (date==startdate)
 {
 }
 if (date<startdate)
 {
 }

【讨论】:

    猜你喜欢
    • 2017-10-23
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多