-
I have the date of birth in the following format: '2014-01-08' I've tried different ways, but without success. const today = new Date() I tried to follow this case -> https://github.com/phiilu/alexa-birthday-countdown/blob/master/index.js if (days === 0) { |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
An anniversary needs to match the month and date but not the year. I suspect that the repo you were referencing doesn't work as intended because Anyhow... if you really just want to check an anniversary, the following should work. You could use import { parseISO } from "date-fns";
function isAnniversary(date, anniversaryString) {
const anniversary = parseISO(anniversaryString);
return (
date.getDate() === anniversary.getDate() && date.getMonth() === anniversary.getMonth()
);
}
const today = new Date();
console.log(isAnniversary(today, "2014-01-08")); // false
console.log(isAnniversary(today, "2010-06-29")); // true
console.log(isAnniversary(today, "2021-06-29")); // true
// Edge case to consider...
// Do leap year babies only have a birthday every 4 years, or do you nudge them into feb 28 on non-leap years?
const leap = "2020-02-29";
console.log(isAnniversary(new Date(2021, 1, 28), leap)); // false
console.log(isAnniversary(new Date(2021, 2, 1), leap)); // false |
Beta Was this translation helpful? Give feedback.
An anniversary needs to match the month and date but not the year. I suspect that the repo you were referencing doesn't work as intended because
differenceInCalendarDays
does takes into account years and can give you differences greater than 365 days. To make that countdown work, the year of one of the dates would need to be changed to match the other's.Anyhow... if you really just want to check an anniversary, the following should work. You could use
parse
too, butparseISO
fits your input format and is lighter. Good luck!