Reputation: 28030
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
Upvotes: 0
Views: 682
Reputation: 4014
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');
}
Upvotes: 4