46

I am absolutely new in JavaScript development and I have to perform the following task: I have 2 input tag 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.

<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 button used to submit this form using this 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 dataDa value (in English language dateFrom).

I am trying to do something like this:

  1. The JavaScript is called at the onchange event 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
        }
    }
    

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

3
  • If you want to use jQuery check datejs To compare dates you can then use Date.compare ( Date date1, Date date2 ) Commented Dec 5, 2014 at 13:55
  • 1
    I don't think you need jQuery for datejs. Another fine date library i used is momentjs.com Commented Dec 5, 2014 at 14:00
  • @VDesign using a library for this simple task is simply absurd. Think before you type Commented Dec 5, 2014 at 14:05

3 Answers 3

72

Very simple, Date instance can be compared directly.

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think this method would be correctly more: ``` function isNearestDate(time1, time2) { const dateTime1 = new Date(time1); const dateTime2 = new Date(time2); if (!isNaN(dateTime1.valueOf()) && !isNaN(dateTime2.valueOf())) { return new Date(time1) >= new Date(time2); // true if time1 is later } return !isNaN(dateTime1.valueOf()); } ```
22

This will work:

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

Returns true if date2 is later, false otherwise. Call with 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

4 Comments

@TrueBlueAussie It's from this answer. Inaccurate to a second, at most.
By why round at all if you are using seconds? Surely you need to truncate to the closest date (i.e. midnight).
@TrueBlueAussie I don't need to divide it at all, really.
You don't even need to use getTime() as dates can be compared directly with >.
13

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" />

1 Comment

There is also a toISOString() that returns the same. What is the difference?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.