-1

I would like to inform the client of his Startuday holyday. The Startuday begins on person.birthday - 9 months.

Having the person.birthday, we need to know if today is his Startuday?

Is there a more elegant/short way to find the date difference in months than the following:

const today = new Date();
const DeltaMonths = 9;

const person = {
  name: 'John',
  birthday: new Date(
    today.getFullYear(),
    today.getMonth() + DeltaMonths,
    today.getDate()  //-2 // uncomment to see the diff
  )};

let futureDate = new Date(
    today.getFullYear(),
    today.getMonth() + DeltaMonths,
    today.getDate());

let diff = person.birthday - futureDate;

if (diff === 0)
  console.log("Horray %s! Today is your startuday!!!", person.name);
else 
  console.log("Sorry %s, today is NOT yet your startuday...", person.name);
serge
  • 13,940
  • 35
  • 121
  • 205
  • what's exactly nine months before halloween ? 40 weeks might be a better measure - it's what doctors use. – Jasen Oct 19 '22 at 00:20
  • @Jasen the business requirement was "9 months", take a look here https://www.timeanddate.com/date/dateadded.html?d1=19&m1=10&y1=2022&type=add&ay=&am=9&aw=&ad=&rec= – serge Oct 19 '22 at 00:23
  • What's the business requirement if today is the 31st but there's no 31st in the month 9 months ago? For example, for 31st of January or similarly for 29th or 30th of November? – Jiří Baum Oct 19 '22 at 00:52
  • 1
    "date difference in months" is somewhat ill-defined, ask for clarification – Jasen Oct 19 '22 at 00:55
  • @Jasen this one is OK https://stackoverflow.com/a/13633692/961631 – serge Oct 19 '22 at 07:35

1 Answers1

0

This should work the same as your code above if I'm understanding it correctly

const deltaMonths = 9;

const birthday = new Date('2023-07-19');
const today = new Date();

today.setMonths(today.getMonths() + deltaMonths);

const diff = today.getTime() - birthday.getTime();

const isTheDay = diff >= 0 && diff < (1000 * 60 * 60 * 24)
asportnoy
  • 2,218
  • 2
  • 17
  • 31
  • Adding months isn't that simple. E.g. Jan 31 plus 1 month will be 2 or 3 March depending on whether it's a leap year. See [*JavaScript function to add X months to a date*](https://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date). – RobG Oct 19 '22 at 06:15
  • @RobG from my understanding of the question, the user's code did what they wanted, they just thought it could be written better. Though from their latest comment, seems like that was not the case. – asportnoy Oct 19 '22 at 15:17