javascript - 一个月内的小时数的数学函数

标签 javascript reactjs react-native math momentjs

是否有数学函数可以计算一个月(不包括周末)的小时数?

假设我使用 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/

相关文章:

autocomplete - react native : Autocomplete text input with tags

javascript - 如何使用麦克风检测声音吹响/尖叫声(用于概念验证)?

javascript - 奇怪的 URL 回调性能。它怎么知道?

javascript - Laravel 显示来自另一个数据库连接的图表

javascript - Javascript ES6 中的静态构造函数

javascript - Webpack 需要什么配置才能完成这些事情?

reactjs - React Router 4 阻止页面重新加载

javascript - React Native 使用代理获取本地服务器

javascript - 使用手机时如何隐藏一个 svg 并显示另一个?

react-native - React Native Navigation with Redux,如何使用?