How to compare two dates using input date and new date object in Javascript

Asked

Viewed 24 times

1

I have two inputs of the kind date. One for the user to enter the start date and the other to enter a final date. I created a variable that receives the current date using only the new Date.

I have a function that checks whether the current date is longer than the final date. If yes, it returns a message. If not, it returns a different message. I tested on two browsers, Firefox and Chrome. In Firefox this function correctly returns the validations. The problem comes now, in Chrome it does not understand the conditions of if and else that I created.

Jsfiddle

window.onload = function () {
    var d1 = document.getElementById('inicio').valueAsDate
    var d2 = document.getElementById('fim').valueAsDate
    var agora = new Date()

    console.log(agora)
    var btn = document.getElementById('btn')

    btn.addEventListener('click', function checkTime() {
        if(agora > d2) {
            console.log('Turma finalizada.')
        } else
            console.log('Turma em andamento.')
    })
}
<input type="date" id="inicio">
<input type="date" id="fim">
<input type="button" value="Clique" id="btn">

1 answer

1


The problem is that in the event of click the variables agora and d2 have the values they had initially, before the click. That is, the value of d2 is not updated (just put a console.log(d2) within its function checkTime to see that she’s always worth it null).

Finally, it would be enough to put the part that takes the values within the correct function. But there’s another detail: a field input type="date" only has the date (day, month and year), but does not have the time (hours, minutes, seconds). Only new Date() creates a date also containing the current time.

Then the comparison takes into account the time. The problem is that the date returned by valueAsDate ends up having the set time for midnight in UTC. Therefore, if you want the comparison not to take into account the time (and only the day, month and year), you need to set the time to midnight:

window.onload = function() {
    var btn = document.getElementById('btn');
    btn.addEventListener('click', function() {
        var d1 = document.getElementById('inicio').valueAsDate;
        var d2 = document.getElementById('fim').valueAsDate;
        var agora = new Date();
        // ajusta o horário para meia-noite em UTC
        agora.setUTCHours(0, 0, 0, 0);
        if(agora > d2) {
            console.log('Turma finalizada.');
        } else {
            console.log('Turma em andamento.');
        }
    });
};
<input type="date" id="inicio">
<input type="date" id="fim">
<input type="button" value="Clique" id="btn">

Note: In the Javascript code, I put semicolon at the end of the lines. It may sound "fresh," and I know that Javascript "accepts" the semicolon code and "works," but it avoids some bizarre situations that can occur if you don’t use them, like that one and that one (see more about this here).

  • 1

    Thank you so much, really. You saved me for today. It’s working perfectly in Chrome too. I’m a beginner in Js and need to study more. I’m glad there’s a stackoverflow :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.