Say I have an array of birthdates
var bdates = ['1956-12-03', '1990-03-09',...]
I'll put each one through a function that will return those dates that have a birthday within 7 days from today (or from now?). What I have at the moment is this:
var bdays = _.map(bdates, function(date) {
var birthDate = new Date(date);
var current = new Date();
var diff = current - birthDate; // Difference in milliseconds
var sevenDayDiff = Math.ceil(diff/31557600000) - (diff/31557600000); //1000*60*60*24*365.25
if (sevenDayDiff <= 0.01916495550992)
return date;
else
return false;
});
The value 0.01995183087435 was determined from taking the number of milliseconds in 51 weeks and dividing by the number of milliseconds in 52 weeks, then one minus that ratio should be the 'sevenDayDiff' variable.
My JSFIDDLE, unfortunately, doesn't quite get it right. There are a number of things wrong with this. My sevenDayDiff could be the wrong value. Also there's the leap year issue too, even if I'm dividing by 365.25. I could be just going about this the wrong way.
This is going in a web app so an administrator can fire off an email to those people who have a birthday within 7 days. Any hints or suggestions are welcome.
var bdates = ['1956-12-03', '1990-03-09', '1970-02-14'];
var now = moment('2015-02-10');
var birthDates = [];
bdates.forEach(function(birthDate) {
var birthDay = moment(birthDate).year(now.year());
var birthDayNextYear = moment(birthDate).year(now.year() + 1);
var daysRemaining = Math.min(Math.abs(birthDay.diff(now, 'days')), Math.abs(birthDayNextYear.diff(now, 'days')));
if((daysRemaining >= 0) && (daysRemaining <= 7)) {
birthDates.push(birthDate);
}
});
document.write(JSON.stringify(birthDates));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With