Romillion
Romillion

Reputation: 159

Compare two Date hours

I have a two times: "02:00" this is hoursValue : minutesValue "02:00" this is hoursValue : minutesValue

var startTime = new Date().setHours("02:00".split(":")[0]);
console.log(startTime);

var endTime = new Date().setHours("2:00".split(":")[0]);
console.log(endTime);

var compare = startTime === endTime;
console.log(compare)

> 1672965757045
> 1672965757046
> false

I noticed that sometimes it returns the different number of milliseconds. why this solution is bad and how to compare two hour when first one started from 0 another no.

Upvotes: 0

Views: 103

Answers (2)

Peter Thoeny
Peter Thoeny

Reputation: 7616

The reason you get a different start and end time is because console.log() and any other action takes time. Just get the star and end time, and compare the hours later:

var startTime = new Date();
console.log('introduce a small delay with console log');
var endTime = new Date();
let diff = endTime.valueOf() - startTime.valueOf();
let compare = startTime.getHours() === endTime.getHours();
console.log({
  startTime,
  endTime,
  diff,
  compare
});

Upvotes: 1

tenshi
tenshi

Reputation: 26404

Why don't you just compare the hours directly?

var startTime = new Date();
startTime.setHours("02:00".split(":")[0]);
console.log(startTime);

var endTime = new Date();
endTime.setHours("2:00".split(":")[0]);
console.log(endTime);

var compare = startTime.getHours() === endTime.getHours();
console.log(compare);

Upvotes: 3

Related Questions