答案 0 :(得分:5)
更新方法(不循环)
您实际上可以利用day()
功能,该功能允许您在moment.js中设置当前星期几以查找基于特定日期的上周五:
function getPreviousWorkday(){
// Based on the current day, handle accordingly
switch(moment().day())
{
// If it is Monday (1),Saturday(6), or Sunday (0), Get the previous Friday (5)
// and ensure we are on the previous week
case 0:
case 1:
case 6:
return moment().subtract(6,'days').day(5);
// If it any other weekend, just return the previous day
default:
return moment().day(today - 1);
}
}
can be seen here并在下面演示:
循环方法
您可以直接从当前时刻通过subtract()
功能从当前时刻减去天数,直到您到达非周末日:
function getPreviousWorkday(){
// Get today
var today = new moment().subtract(-1,'days');;
// If today isn't a weekend, continue iterating back until you hit a non-weekend
while([0,6].indexOf(today.day()) !== -1){
today = today.subtract(1, 'days');
}
// Return the non-weekend day
return today;
}
你可以see an example of this in action here并在下面演示:
答案 1 :(得分:5)
function getPreviousWorkday(){
let workday = moment();
let day = workday.day();
let diff = 1; // returns yesterday
if (day == 0 || day == 1){ // is Sunday or Monday
diff = day + 2; // returns Friday
}
return workday.subtract(diff, 'days');
}
答案 2 :(得分:1)
function getPreviousWorkday() {
return [1, 2, 3, 4, 5].indexOf(moment().subtract(1, 'day').day()) > -1 ?
moment().subtract(1, 'day') : moment(moment().day(-2));
}
如果前一天是工作日,则返回前一天/工作日。否则返回上一个星期五,如果前一天是星期六或星期日,它应该返回上一个星期五。
答案 3 :(得分:1)
有一个npm模块!
https://github.com/kalmecak/moment-business-days
来自文档:
prevBusinessDay():将检索上一个营业日期作为时刻日期对象:
//Previous busines day of Monday 02-02-2015
moment('02-02-2015', 'DD-MM-YYYY').prevBusinessDay()._d // Fri Jan 30 2015 00:00:00 GMT-0600 (CST)
//Previous busines day of Tuesday 03-02-2015
moment('03-02-2015', 'DD-MM-YYYY').prevBusinessDay()._d //Mon Feb 02 2015 00:00:00 GMT-0600 (CST)
P.S:重要节点。为什么要使用依赖?如果你需要的只是上一个工作日 - 没有理由使用3-d party lib。但对于实际应用,所有这些内容对于更复杂的操作非常有用,例如根据日历,假期等导入日期,格式和计算。