Time Comparison

I have two times startTime: "18:10" endTime: "18:55" Now I want to compare the current time with these So if the current time is before startTime I want to return -1 If the current time is after the end time I want to return 1 And if the current time is between start and end time I want to return 0 I tried to implement using if else but it's getting to Complex and its not accurate too. Can anyone help me build logic for this?
1 Reply
Matvey
Matvey9mo ago
const startTime = "18:10";
const endTime = "18:55";

const timeStringToTimestamp = (time: string) => {
const [hours, minutes] = time.split(":").map((n) => parseInt(n));
const now = new Date();
const date = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes
);
return date.getTime();
};

const compareTimes = (startTime: string, endTime: string) => {
const start = timeStringToTimestamp(startTime);
const end = timeStringToTimestamp(endTime);
const now = Date.now();
if (start > now) return -1;
if (end > now) return 1;
return 0;
};

console.log(compareTimes(startTime, endTime));
const startTime = "18:10";
const endTime = "18:55";

const timeStringToTimestamp = (time: string) => {
const [hours, minutes] = time.split(":").map((n) => parseInt(n));
const now = new Date();
const date = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes
);
return date.getTime();
};

const compareTimes = (startTime: string, endTime: string) => {
const start = timeStringToTimestamp(startTime);
const end = timeStringToTimestamp(endTime);
const now = Date.now();
if (start > now) return -1;
if (end > now) return 1;
return 0;
};

console.log(compareTimes(startTime, endTime));
convert the time to unix timestamps, then it's super easy to compare
Want results from more Discord servers?
Add your server