Home > Enterprise >  Compare two Date hours
Compare two Date hours

Time:01-07

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

check this other way you can use libs like date-fns there is a function called compared which you can use it to compare two dates Link to docs https://date-fns.org/v2.29.3/docs/compareAsc.

import compareAsc from 'date-fns/compareAsc'

const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))

function compareHours(time1, time2) {
  const [hour1, minute1] = time1.split(":");
  const [hour2, minute2] = time2.split(":");
  return Number(hour1) === Number(hour2) && Number(minute1) === Number(minute2);
}

console.log(compareHours("02:00", "02:00")); // true
console.log(compareHours("02:00", "2:00")); // true
console.log(compareHours("02:00", "03:00")); // fals

This function compares the hours and minutes of the two time strings and returns true if they are the same and false otherwise.

  • Related