Tuesday, May 17, 2022

[FIXED] How to perform partial date comparison, ignoring the year, in javascript?

Issue

As the title says, I'd like to write some basic code that checks if the month, and the day of a given JavaScript Date object fall between a certain range. I know that to compare regular dates, one can do the following...

date1 < date2 && date2 > date3

But how would one access only the month and the day? I know the Date object can return both it's month and it's day, but I'm honestly stumped as to how one could compare only them.


Solution

You can extract a comparable "key" from your date (eg. month*100+day) and compare these keys as numbers:

function compareByMD(date1, date2) {
    let a = date1.getMonth() * 100 + date1.getDate();
    let b = date2.getMonth() * 100 + date2.getDate();
    return (a > b) - (a < b);
}

//

console.log(
    [
        new Date(2009, 7, 15),
        new Date(2011, 8, 3),
        new Date(2019, 5, 3),
        new Date(2022, 7, 13),
    ].sort(compareByMD)
)



Answered By - georg
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.