Reputation: 27465
Looking solution to alert when today is the birthday. Here comparing Day and Month in isSame()
Very unfortunately the isSame()
not comparing day with given date. Also not getting true for month when year is different.
Looking for javascript to find user's birth day
const dateOfBirth = moment("2018-09-07T13:36:14.000Z").format("DD-MM-YYYY");
const today = moment(new Date()).format("DD-MM-YYYY");
if (
moment(dateOfBirth).isSame(today, "day") &&
moment(dateOfBirth).isSame(today, "month")
) {
console.log("Today is your birth day");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Upvotes: 1
Views: 528
Reputation: 5504
Momentjs has an api to check whether or not a certain date is the same.
As arguments it takes the date object, instead of the formatted strings.
In order to check for any year, just use a trick: set the year of the object to todays year.
Example:
// Date in any year
const dateOfBirth = moment("2018-09-07T13:36:14.000Z");
// Set year to current year
dateOfBirth.year(moment().year());
// Compare to today
console.log('Is it your birthday?', dateOfBirth.isSame(new Date(), "day"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
It is also possible to make a copy of the variable, so that the original can stay the same.
Upvotes: 1