PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

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

 May 17, 2022     comparison, date, javascript, object, partial     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing