【问题标题】:How do I compare two dates in HTML? [duplicate]如何比较 HTML 中的两个日期? [复制]
【发布时间】:2016-01-12 15:24:04
【问题描述】:

这是我的代码:

<input type="date" name="startDate" id="startDate" />
<input type="date" name="endDate" id="endDate" />

我希望startdate 不超过endDate。有没有办法在不使用 jQuery 的情况下比较日期?就像在 ASP.NET 中一样,我们可以使用 CompareValidator。

【问题讨论】:

标签: html date validation html-input


【解决方案1】:

您需要为此使用 JavaScript。

function compare()
{
    var startDt = document.getElementById("startDate").value;
    var endDt = document.getElementById("endDate").value;

    if( (new Date(startDt).getTime() < new Date(endDt).getTime()))
    {
        // Your code here
    }
}
&lt;input type="date" name="endDate" id="endDate" onblur="compare();"/&gt;

也进行必要的 null 验证。

【讨论】:

  • 正确的API是获取valueAsDate属性。这个答案的作用是将字符串从value 属性传递给Date 构造函数,这是错误的。 “注意:由于浏览器的差异和不一致,强烈建议不要使用 Date 构造函数(和 Date.parse,其工作方式相同)解析日期字符串。” — 来自documentation
猜你喜欢
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2015-08-28
  • 2016-01-05
  • 2011-01-13
相关资源
最近更新 更多