1

I have two string for time, one is current time and the other one is twenty minutes later. Here is the output:

10/1/2017 1:20:58 PM
10/1/2017 1:40:58 PM

Here is the code:

var now = new Date();
console.log(now.toLocaleDateString() + " " + now.toLocaleTimeString());
var in20 = new Date(now.getTime() + (1000*60*20));
console.log(in20.toLocaleDateString() + " " + in20.toLocaleTimeString());

Is there any way to check if the variable for twenty minutes later is before or after the current time variable as I not sure how to make time comparison based on two time strings. If it is after current time variable, return a true, otherwise return a false.

Any ideas? Thanks!

QWERTY
  • 2,303
  • 9
  • 44
  • 85
  • Could you please try rewording your question? It is very difficult to understand what exactly you're trying to do. – Graham Oct 01 '17 at 05:28
  • Possible duplicate of [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Graham Oct 01 '17 at 05:29

1 Answers1

1

Best way to compare the 2 time string is convert them to milliseconds and then compare. For Eg.

var now = new Date();
console.log(now.toLocaleDateString() + " " + now.toLocaleTimeString());
var in20 = new Date(now.getTime() + (1000*60*20));
console.log(in20.toLocaleDateString() + " " + in20.toLocaleTimeString());

// at any instant suppose now is cuurent time then you can compare like

if(now.getTime() > in20.getTime()) {
  console.log('current is greater')
} else {
  console.log('in20 is greater')
}
Arun Redhu
  • 1,584
  • 12
  • 16