是否有数学函数可以计算一个月(不包括周末)的小时数?
假设我使用 MomentJS
获取一个月中的天数。一个工作日有 7:36 小时,每周有 5 天必须工作(不包括周末)。
例如,如果该月有30天,并且我知道每天有7:36小时(7小时36分钟),但我需要排除这个月的每个周末这样的函数会是什么样子/是否有可能有这样的函数?我需要它在 React Native 和 JavaScript 中工作。
最佳答案
计算工作日
const pad = num => ("0" + num).slice(-2);
const minutesPerDay = 7 * 60 + 36; // or 7.6 hours
const isWorkingDay = d => d.getDay() !== 0 && d.getDay() !== 6;
const getHHMM = m => `${Math.floor(m / 60)}:${pad(m % 60)}`;
const getHours = (year, month) => {
const startDate = new Date(year, month - 1, 1, 15, 0, 0); // we need a date object
const endDay = new Date(year, month, 0).getDate(); // and number of days in the month
console.log("start", new Date(startDate), "end", "+" + endDay)
let workingDays = 0;
for (let i = 1; i <= endDay; i++) { // count from 1 to and including last day of month
startDate.setDate(i); // reuse startdate object
workingDays += isWorkingDay(startDate) ? 1 : 0; // if 0 or 6, ignore
}
return getHHMM(workingDays * minutesPerDay); // format to HH:MM
};
console.log(getHours(2020, 1)); // jan
console.log(getHours(2020, 2)); // feb
关于javascript - 一个月内的小时数的数学函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60109773/