Compare system time to set time in a variable

Asked

Viewed 676 times

2

How do I compare system time to a time set in a variable in jQuery or Javascript?

  • "system time" is the user in the browser, or the server? The variable has time information in what format?

  • browser user

  • 3

    And what is in the variable is in what format? timestamp? ISO?

  • for example - 14:50:00

1 answer

3


Suggestion:

function compararHora(str) {
    str = str.split(':');
    var agora = new Date();
    var varData = new Date();
    ['setHours', 'setMinutes', 'setSeconds'].forEach(function(fn, i) {
        return varData[fn](str[i]);
    });
    if (agora == varData) return 0;
    else return agora > varData ? 1 : -1;
}



console.log(compararHora('05:50:00'));
console.log(compararHora('23:50:00'));

Starting from the format you indicated hh:mm:ss, you can break that string by : and use the methods Javascript gives us to change the time to a date. Then compare if the time is the same, "greater than" or "less than", and in the function I suggest returns respectively 0, 1 or -1;

  • 1

    It worked! Thank you Sergio!

Browser other questions tagged

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