需求:前端计算工厂的工作时间,早班(早上8点到晚上20点)晚班(晚上20点到第二天的早上8点)中间包括年月的加减
例如:[2022-11-28 08:00:00 2022-11-28 20:00:00]
const time = new Date();
// 开始时间,结束时间
let preTime, endTime;
const currentMonth = time.getMonth();
const H = time.getHours();
const PREHH = H >= 8 && H < 20 ? "08:00:00" : "20:00:00";
let ENDHH,
endYear = time.getFullYear(),
endMonth = time.getMonth() + 1,
endDay = time.getDate(),
preYear = time.getFullYear(),
preMonth = time.getMonth() + 1,
preDay = time.getDate();
if ((H <= 24 && H >= 20) || H < 8) {
if (H <= 24 && H >= 20) {
if (currentMonth == new Date(time * 1 + 24 * 60 * 60 * 1000).getMonth()) {
endDay = time.getDate() + 1;
} else {
const time2 = new Date(time * 1 + 24 * 60 * 60 * 1000);
endYear = time2.getFullYear();
endMonth = time2.getMonth() + 1;
endDay = time2.getDate();
}
}
if (H < 8) {
if (currentMonth == new Date(time * 1 - 24 * 60 * 60 * 1000).getMonth()) {
preDay = time.getDate() - 1;
} else {
const time2 = new Date(time * 1 - 24 * 60 * 60 * 1000);
preYear = time.getFullYear();
preMonth = time2.getMonth() + 1;
preDay = time2.getDate();
}
}
ENDHH = "08:00:00";
} else {
ENDHH = "20:00:00";
}
preTime = `${preYear}-${preMonth < 10 ? `0${preMonth}` : preMonth}-${preDay < 10 ? `0${preDay}` : preDay} ${PREHH}`;
endTime = `${endYear}-${endMonth < 10 ? `0${endMonth}` : endMonth}-${endDay < 10 ? `0${endDay}` : endDay} ${ENDHH}`;
return [preTime, endTime];
}