如何使用 JavaScript\JQuery 检查一个日期是否在另一个日期之前?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27317437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:00:33  来源:igfitidea点击:

How to check if one date is before another date using JavaScript\JQuery?

javascriptjqueryjavascript-events

提问by AndreaNobili

I am absolutly new in JavaScript development and I have to perform the following task: I have 2 inputtag containing 2 string representing date in the form 01/12/2014(DAY/MONTH/YEAR). I use this input tag to search objects that have a date field that is among these dates.

我绝对是 JavaScript 开发的新手,我必须执行以下任务:我有 2 个输入标签,其中包含 2 个字符串,以01/12/2014( DAY/MONTH/YEAR)的形式表示日期。我使用此输入标记来搜索具有这些日期中的日期字段的对象。

<input type="hidden" size="9" class="impPrfTot" readonly="readonly"
                                           onchange="cambioDataDa(this.value)"
                                           name="dataDa" id="datada" value="<%=request.getSession().getAttribute("dataDa")%>"
                                           style="font-size: 11px;color: #000000;">

<input type="hidden" size="9" class="impPrfTot" readonly="readonly"
                                           onchange="cambioDataA(this.value); checkData(this.value)"
                                           name="dataA" id="dataa" value="<%=request.getSession().getAttribute("dataA")%>"
                                           style="font-size: 11px;color: #000000;">

<button class="dataDadataAButton" name="submitdataDadataA" onclick="sottomettiFormDataDaA(this)">Cerca</button>

And finally I have a buttonused to submit this form using this JavaScript:

最后,我有一个按钮用于使用此 JavaScript 提交此表单:

function sottomettiFormDataDaA(obj) {
    document.getElementById('dataDaAForm').submit();
}

What I need is to prevent that the value inside dataA(in English language dateTo) input is previous that dataDavalue (in English language dateFrom).

我需要的是防止里面的值数据A(中英文dateTo)方法的输入是以前的那个dataDa值(以英语dateFrom)。

I am trying to do something like this:

我正在尝试做这样的事情:

  1. The JavaScript is called at the onchangeevent on the change of a data and take the dataA string (tha represent the dateTo date) and check if it is previous of the dataA (the dateTo date).

  2. If the previous check is true the date range is invalid so the script show an error popup message and disallow the submit of the form having id="dataDaAForm"

    function checkData(dataA) {
        dataDa = document.getElementById('dataDa').value;
    
        if(dataDa > dataA){
            // SHOW A POPUP ERROR MESSAGE
            // DISALLOW THE FORM SUBMIT
        }
    }
    
  1. JavaScript 在数据更改的onchange事件中被调用,并获取 dataA 字符串(代表 dateTo 日期)并检查它是否是 dataA(dateTo 日期)的前一个。

  2. 如果先前的检查为真,则日期范围无效,因此脚本会显示错误弹出消息并禁止提交具有 id="dataDaAForm" 的表单

    function checkData(dataA) {
        dataDa = document.getElementById('dataDa').value;
    
        if(dataDa > dataA){
            // SHOW A POPUP ERROR MESSAGE
            // DISALLOW THE FORM SUBMIT
        }
    }
    

Bue I have really not idea about complete this JavaScript and I don't know it exist better solution to achieve this task.

但是我真的不知道完成这个 JavaScript 并且我不知道它存在更好的解决方案来完成这个任务。

采纳答案by Yaseen

If you only need to compare the date without the time use this:

如果您只需要比较没有时间的日期,请使用以下命令:

// convert date format to "YYYY-MM-DD"
var a = new Date().toJSON().slice(0, 10)
// get date from input field, by default is "YYYY-MM-DD" format
var b = document.getElementById('datePicker').value

// compare
console.log(a == b)
console.log(a > b)
console.log(a < b)
<input id="datePicker" type="date" />

回答by Leo

Very simple, Dateinstance can be compared directly.

很简单,Date实例可以直接比较。

function compareTime(time1, time2) {
    return new Date(time1) > new Date(time2); // true if time1 is later
}

When you compare two Dateinstance, or minus one another, the valueOfmethod will be called internally, which convert the instance to timestamp (millisecond accurate).

当您比较两个Date实例或减去另一个实例时,valueOf将在内部调用该方法,将实例转换为时间戳(精确毫秒)。

回答by Mooseman

This will work:

这将起作用:

function dateCompare(date1, date2){
    return new Date(date2) > new Date(date1);
}

Returns trueif date2is later, falseotherwise. Call with dateCompare('01/12/2014', '02/24/2014').

true如果date2较晚false则返回,否则返回。用 呼叫dateCompare('01/12/2014', '02/24/2014')

function dateCompare(date1, date2){
    return new Date(date2) > new Date(date1);
}

// Demo (uses jQuery)

$("tbody tr").each(function(){
    $tr = $(this);
    $td = $tr.children('td');
    date1 = $td.eq(0).text();
    date2 = $td.eq(1).text();
    result = dateCompare(date1,date2);
    $td.eq(2).text(result);
    if($td.eq(2).text() == $td.eq(3).text()) $tr.css('background','green');
    else $tr.css('background','red');
});
table{
    border-collapse: collapse;
}
td{
    padding: 5px;
    border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <td>date1</td>
            <td>date2</td>
            <td>Result</td>
            <td>Expected</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>01/12/2014</td>
            <td>02/24/2014</td>
            <td></td>
            <td>true</td>
        </tr>
        <tr>
            <td>01/12/2013</td>
            <td>02/24/2012</td>
            <td></td>
            <td>false</td>
        </tr>
        <tr>
            <td>01/12/2014</td>
            <td>02/24/2018</td>
            <td></td>
            <td>true</td>
        </tr>
        <tr>
            <td>01/12/2015</td>
            <td>02/24/2011</td>
            <td></td>
            <td>false</td>
        </tr>
    </tbody>
</table>

I also made a fiddle, if you prefer.

如果你愿意,我也做了一个小提琴

Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

进一步阅读:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date