说我有一系列生日
var bdates = ['1956-12-03', '1990-03-09',...]
我会把每个人都通过一个函数来返回那些从今天(或从现在开始)7天内生日的日期。我现在所拥有的是:
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;
});
值0.01995183087435是根据51周内的毫秒数除以52周内的毫秒数确定的,然后减去该比率应为'sevenDayDiff'变量。
不幸的是,我的JSFIDDLE并没有完全正确。这有很多问题。我的sevenDayDiff可能是错误的价值。还有闰年问题,即使我除以365.25。我可能只是走错了路。
这是在网络应用中进行的,因此管理员可以向7天内过生日的人发送电子邮件。欢迎任何提示或建议。
答案 0 :(得分:1)
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>