简体   繁体   中英

Improvement to this code to compare 2 time in format (HH:MM:SS)

I wrote some code to compare 2 time in string format (HH:MM:SS).

var time = new Date();
var current_time_str = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();

var deadline= "16:00:00" //hh:mm:ss
if ( (current_time_str) > (deadline))
{
    console.log("deadline has passed");
}

The code actually works by simply comparing the string. However, I am worried if it worked only coincidentally by luck because the string is just an ASCII representation. Are there other ways to compare the 2 time? I am using node.js

Generally speaking it's safer to compare two Date objects than it is to compare strings.

You can do something like this:

// Get current date/time
var now = new Date();

// Set up deadline date/time
var deadline = new Date();
deadline.setHours(16);
deadline.setMinutes(0);

// Check if the current time is after the deadline
if( now > deadline ) {
    alert('after deadline');
}
else {
    alert('before deadline');
}

http://jsfiddle.net/md63mbpd/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM