Basel
Basel

Reputation: 1365

How to compare time in javascript?

I have two time in the format "HH:MM" i want to compare them i have the following code to get the time of now in my format:

current_time = new Date();
hour = current_time.getHours();
minute = current_time.getMinutes();
if(hour<10){hour='0'+hour} if(minute<10){minute='0'+minute}
my_time = hour+':'+minute;

And this code is to get the time after subtracting the GMT difference :

d = new Date()
var n = d.getTimezoneOffset();
var n1 = Math.abs(n);
var difference = (n1/60); 
my_time = my_time - (0+difference);

Now the value of my_time should be compared with the value of match_time:

match_time = 10:00;//for example
if(my_time > match_time)
{
  alert('yes');
}
else
{
  alert('No');
}

how can I compare those values as time when they are a string ???

Upvotes: 41

Views: 116071

Answers (7)

Igor Grechishkin
Igor Grechishkin

Reputation: 476

Assuming you are not interested in time zones and only need to compare two formatted time strings in 24h time format, you can just compare strings.

let time1 = '09:12';
let time2 = '12:22';

if (time1 > time2) {
 alert('yes')
} else {
 alert('no')
}

It works because strings in JS are compared symbol by symbol. So when compared '09:12' > '12:22' JS first checks if '0' == '1' and if false '0' > '1', and then returns result.

For comparison of strings '01' > '02', it will check if '0' == '0' then skip to next symbol in both strings and compare '1' > '2' which is false.

Strings has to be normalized to hh:mm, otherwise you will get unexpected results like:

"9:12" > "12:22" //true

Upvotes: 33

Pearce
Pearce

Reputation: 41

Similar to @Arjun Sol, instead of using Date.parse, you could just grab the times from the string itself, create a new Date object and do the comparison.

const time1 = '12:42';
const time2 = '18:30';

const getTime = time => new Date(2019, 9, 2, time.substring(0, 2), time.substring(3, 5), 0, 0);

const result = getTime(time1) < getTime(time2);
console.log('This should be true:', result);

Upvotes: 2

saidesh kilaru
saidesh kilaru

Reputation: 748

 if(Date.parse('01/01/2011 10:20:45') == Date.parse('01/01/2011 5:10:10')) {
  alert('same');
  }else{

  alert('different');

  }

The 1st January is an arbitrary date, doesn't mean anything.

Upvotes: 1

Ragulan
Ragulan

Reputation: 1711

we can do some hack with.

var time1 = "09:30";
var time2 = "10:30";
var time1Date= new Date("01/01/2000 "+time1);
var time2Date= new Date("01/01/2000 "+time2);

if(time1Date >= time2Date ){
    console.log("time1");
}else{
    console.log("time2");
}

Upvotes: 1

TMurphy
TMurphy

Reputation: 73

If I had enough reps to vote for @Gabo Esquivel solution. For days I have searched for and tested solutions and this is the only one that worked for me.

I needed a conditional statement testing if the current time is 0830 and if so, do something. My if statement was not working so I needed other examples to work with.

//Business Hours: Saturday 8:30am-12pm; highlight Saturday table row.
function showSaturdayHours() {
    var today = new Date();
    var weekday = today.getDay();
    var saturdayOpen = new Date();
    saturdayOpen.setHours(8, 30, 0);
    var saturdayClose = new Date();
    saturdayClose.setHours(12, 0, 0);

if (weekday == 6) {
    $('#saturday-row').addClass('row-blue'); //highlight table row if current day is Saturday.
    if (today >= saturdayOpen && today < saturdayClose) {
        document.getElementById('saturday-open').innerHTML = 'Open';
    } else {
        document.getElementById('saturday-open').innerHTML = 'Closed';
    }
  }
}

Business Hour Table : JSFiddle

Upvotes: 2

Gabo Esquivel
Gabo Esquivel

Reputation: 4002

use Date objects. Date.setHours() allows you to specify hour, minutes, seconds

var currentD = new Date();
var startHappyHourD = new Date();
startHappyHourD.setHours(17,30,0); // 5.30 pm
var endHappyHourD = new Date();
endHappyHourD.setHours(18,30,0); // 6.30 pm

console.log("happy hour?")
if(currentD >= startHappyHourD && currentD < endHappyHourD ){
    console.log("yes!");
}else{
    console.log("no, sorry! between 5.30pm and 6.30pm");
}

Upvotes: 36

Arjun Sol
Arjun Sol

Reputation: 741

Date.parse('25/09/2013 13:31') > Date.parse('25/09/2013 9:15')

EDIT:

Note that you are parsing an arbitrary date that you're not interested in, it just needs to be the same on both sides.

Upvotes: 8

Related Questions