【问题标题】:Number of working days between two dates in Google Apps ScriptGoogle Apps 脚本中两个日期之间的工作日数
【发布时间】:2015-06-03 17:02:54
【问题描述】:

谁能帮助在 Google Apps 脚本中生成两个日期之间的工作日数。 谢谢。

【问题讨论】:

  • stackoverflow.com/questions/29090867/… 的答案显示了如何在 momentjs 和 vanilla js 中做到这一点。 momentJS 应用脚本库是 MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48。
  • 真的是这个问题的重复。它不是特定于应用程序脚本。纯javascript

标签: google-apps-script google-apps


【解决方案1】:

根据此处给出的答案:How do I calculate number of given weekday between range using Moment JS? 它在 AppsScript 中的工作方式类似

function workdays_between(start_date_string, end_date_string) {
  var startDate = new Date(start_date_string)
  var endDate = new Date(end_date_string)

  // Validate input
  if (endDate <= startDate) { return 0; }

  // Calculate days between dates
  var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
  startDate.setHours(0, 0, 0, 1);  // Start just after midnight
  endDate.setHours(23, 59, 59, 999);  // End just before midnight
  var diff = endDate - startDate;  // Milliseconds between datetime objects    
  var days = Math.ceil(diff / millisecondsPerDay);

  // Subtract two weekend days for every week in between
  var weeks = Math.floor(days / 7);
  days -= weeks * 2;

  // Handle special cases
  var startDay = startDate.getDay();
  var endDay = endDate.getDay();

  // Remove weekend not previously removed.   
  if (startDay - endDay > 1) { days -= 2; }
  // Remove start day if span starts on Sunday but ends before Saturday
  if (startDay == 0 && endDay != 6) { days--; }
  // Remove end day if span ends on Saturday but starts after Sunday
  if (endDay == 6 && startDay != 0) { days--; }

  return days
}

function test_it() {
  let start_date_string = "March 12, 2021"
  let end_date_string = "October 15, 2021"
  console.log(workdays_between(start_date_string, end_date_string) + " workdays between " + start_date_string + " and " + end_date_string)
}

【讨论】:

    【解决方案2】:

    来自用户 KBA (https://stackoverflow.com/users/453331/kba) 来自响应 How do I calculate number of given weekday between range using Moment JS?

    var firstDate = new Date("March 1, 2015");
    var secondDate = new Date("March 25, 2015");
    
    function getWeekdaysBetweenDates(firstDate, secondDate, dayOfWeek) {
        var MILISECONDS_IN_DAY = 86400000;
    
        function getNextDayOfWeek(date, dayOfWeek) {
            date.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);
            return date;
        }
    
        firstDate = getNextDayOfWeek(firstDate, dayOfWeek);
        if (firstDate > secondDate) {
            return 0;
        }
    
        return 1 + Math.floor(((secondDate - firstDate) / MILISECONDS_IN_DAY) / 7);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多