我对javascript和moment.js很新。我正在一个网站上工作,我们需要列出产品的下五个可能的提货日期,不包括周末和假日。我有一个开始,使用我在网上找到的功能。它适用于跳过周末,但我不能让假期工作。任何帮助,将不胜感激。 http://jsfiddle.net/rLjQx/940/
moment.fn.addWorkdays = function(days) {
var increment = days / Math.abs(days);
var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
var remaining = days % 5;
while (remaining != 0) {
date.add(increment, 'days');
// Check for weekends and a static date
if (!(date.isoWeekday() === 6) && !(date.isoWeekday() === 7) && !(date.date() === 1 && date.month() === 4)) {
remaining -= increment;
}
}
return date;
};
for (count = 0; count < 5; count++) {
var test = moment().addWorkdays(count + 1).format('dddd, MMMM Do YYYY');
document.write("Pickup date : " + test);
document.write("<br />");
}
答案 0 :(得分:2)
使用我的moment-holiday插件,这是一个快速简便的解决方案。 :)
function getNextWorkDays(count, format) {
if (!count) { count = 5; }
if (!format) { format = 'dddd, MMMM Do YYYY'; }
var days = [];
var d = moment().startOf('day');
for (i = 0; i < count; i++) {
d.add(1, 'day');
if (d.day() === 0 || d.day() === 6 || d.isHoliday()) {
count++;
continue;
}
days.push(moment(d).format(format));
}
return days;
}
var days = getNextWorkDays();
alert("The following days are available for pickup:\n\n" + days.join("\n"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdn.rawgit.com/kodie/moment-holiday/v1.2.0/moment-holiday.js"></script>