guagay_wk
guagay_wk

Reputation: 28030

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

Upvotes: 0

Views: 682

Answers (1)

Tim Sheehan
Tim Sheehan

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');
}

http://jsfiddle.net/md63mbpd/

Upvotes: 4

Related Questions