I have two dates that are UTC
"2022-11-01T22:16:19.844Z" // <-- in the past but later in the day
"2022-11-08T20:16:19.844Z" // <--- in the future but earlier in the day
The first date is < the second date BUT it is later in the day...
I am trying to return the date the is the earliest in the day ex the least amount of hours and minutes... I dont want to return the date that is in the past, ONLY the date that occurs earliest in the day
I have tried
const date_a = new Date("2022-11-01T22:16:19.844Z").getTime()
const date_b = new Date("2022-11-08T20:16:19.844Z").getTime()
//this is always comparing the ENTIRE date, which will return date_a as the lessor when in reality what I want is date_b because it is actually occuring earlier in the day...
CodePudding user response:
Time Sorting
When doing date comparisons it's often simpler to compare strings rather than doing a numerical comparison of hours, minutes, seconds, and milliseconds. And for this problem we could compare the UTC time string of each date, which can be parsed from the date using:
.toISOString() --> "2022-11-10T20:16:19.843Z"
.split("T") --> ["2022-11-10", "20:16:19.843Z"]
.pop() --> "20:16:19.843Z"
And then we sort the time strings using .localeCompare() and return the first element of the array:
let value = dates.sort((a,b) =>
a.toISOString().split("T").pop().localeCompare(
b.toISOString().split("T").pop()
)
)[0];
The code could be simplified for use with local times by using .toTimeString() which wouldn't require the split and pop steps.
Snippet
let dates = [
new Date("2022-11-10T20:16:19.843Z"),
new Date("2022-11-01T22:16:19.844Z"),
new Date("2022-11-08T20:16:19.844Z")
];
let value = dates.sort((a,b) =>
a.toISOString().split("T").pop().localeCompare(
b.toISOString().split("T").pop()
)
)[0];
console.log(value);
CodePudding user response:
You can use Date.prototype.setYear(), setMonth() and set Day() and set the first part of both dates to 0, and then do the comparison.