0

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

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • You can use the fantastic Moment.js library; this library has ALL the functions you'll ever need for date-time manipulation. Read about it http://momentjs.com/ and a similar question http://stackoverflow.com/a/22601120/3102854. – weirdpanda Nov 09 '15 at 09:24
  • Thanks. I did look into moment.js. However, there is a problem. moment need objects that come with a date (DD-MM-YYYY). I only need to compare time (HH-MM-SS). Don't think I can use moment.js in this case. – guagay_wk Nov 09 '15 at 09:26
  • you can try `var d = new Date(); d.toTimeString();` This will return string with timezone which you can split. – Rajesh Nov 09 '15 at 09:29

1 Answers1

4

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/

Tim Sheehan
  • 3,994
  • 1
  • 15
  • 18