简体   繁体   English

计算 javascript 中 2 个时间戳参数之间的工作日和周末小时数

[英]Calculate the number of weekday and weekend hours between 2 timestamp params in javascript

I want to calculate the number of weekday-hours and weekend-hours within a given 2 timestamp range.我想计算给定 2 个时间戳范围内的工作日小时数和周末小时数。 It is sure the timestamp ranges are in hours, it doesn't contain minutes or seconds values in it.可以确定时间戳范围以小时为单位,其中不包含分钟或秒值。

attempt:试图:

function getWeekdayWeekendHours(fromTimestamp, tillTimestamp) {
  let weekdayhours = 0;
  let weekendhours = 0;
  // fix the GMT issue by decreasing timestamp by 5:30
  const fromTime = fromTimestamp - 19800;
  const tillTime = tillTimestamp - 19800;

  let currentDate = new Date(fromTime * 1000);
  const tillDate = new Date(tillTime * 1000);
  while (currentDate < tillDate) {
    if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) 
    weekdayhours += 1;
    else weekendhours += 1;
    currentDate = currentDate.addHours(1);
  }
  return { weekdayhours, weekendhours };
}

// eslint-disable-next-line no-extend-native
Date.prototype.addHours = function (h) {
  this.setHours(this.getHours() + h);
  return this;
};

Here's a function that should work, provided you don't mind using lodash & moment.这是一个应该可以工作的 function,前提是您不介意使用 lodash 和 moment。

const moment = require("moment")
const lodash = require("lodash")

function getHours(ts1, ts2) {
    const weekends = [6, 7] // the isoWeekday of saturday & sunday
    const [m1, m2] = [moment(ts1), moment(ts2)].sort()  // makes sure earlier ts is first
    const numDays = Math.ceil(m2.diff(m1, "days", true)) + 1

    let weekdayHrs = 0
    let weekendHrs = 0
    lodash.range(numDays).forEach(idx => {
        let diffHours = 0
        let start
        let end

        // figure out start, end timestamps
        switch (idx) {
            case 0:
                start = m1
                end = m1.clone().add(1, "days").hours(0).minutes(0).seconds(0).milliseconds(0)
                break
            case numDays - 1:
                end = m2
                start = m2.clone().hours(0).minutes(0).seconds(0).milliseconds(0)
                break
            default:
                start = m1.clone().hours(0).minutes(0).seconds(0).milliseconds(0).add(idx, "days")
                end = start.clone().add(1, "days")
                end = end.isBefore(m2) ? end : m2
                break
        }

        diffHours = end.diff(start, "hours")
        const dayOfWeek = start.isoWeekday()
        const isWeekend = weekends.includes(dayOfWeek)
        if (isWeekend) {
            weekendHrs += diffHours
        } else {
            weekdayHrs += diffHours
        }

        // you can remove these 2 lines from the function. This just prints the total per day.
        const names = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] 
        console.log(idx, names[dayOfWeek - 1], start.format("MMM/DD hh:mm A"), "to", end.format("MMM/DD hh:mm A"), "=", diffHours,  isWeekend ? "weekend hrs": "hrs")
    })

    return { weekdayHrs, weekendHrs, total: weekdayHrs + weekendHrs }
}

Here is some example output:以下是 output 的一些示例:

const ts1 = new Date(2019, 9, 18) // Oct 18 2019 12:00 AM
const ts2 = new Date(2019, 9, 25) // Oct 25 2019 12:00 AM
console.log(getHours(ts1, ts2))

// output:= { weekdayHrs: 120, weekendHrs: 48, total: 168 }


const ts3 = new Date(2019, 9, 18, 10) // Oct 18 2019 10:00 AM
const ts4 = new Date(2019, 9, 22, 13) // Oct 22 2019 1:00 PM
console.log(getHours(ts3, ts4))

// output:= { weekdayHrs: 64, weekendHrs: 48, total: 112 }


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM