计算日期之间的具体工作日数 [英] Calculate number of specific weekdays between dates

查看:188
本文介绍了计算日期之间的具体工作日数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Tasker中的两个日期之间计算周一,周三和周五的数量,因此我需要一个数学公式,可能利用秒数形式的日期,即unix时间或JavaScript代码。我已经尝试了谷歌搜索,并以我的大脑为任何方式,甚至开始这个,我迷路了,所以我还没有尝试任何东西。我唯一可以想到的是得到总天数除以7,但这显然不会帮助我,特别是如果一个或两个时间是周中。任何人都可以指出我有更好的方向吗?

I'm trying to calculate the number of Mondays, Wednesdays, and Fridays between 2 dates in Tasker, thus I need a math formula, possibly utilizing the date in seconds form, i.e. unix time, or a javascript code. I've tried Googling and racking my brain for any way to even start this and I'm lost so I haven't tried anything yet. The only thing I could think of was getting the total number of days and dividing by 7, but that clearly does not help me very much, especially if one or both of the days is midweek. Can anyone point me in a better direction?

推荐答案

如何计算具体日期在O(1)中的两个日期之间的一周中

// days is an array of weekdays: 0 is Sunday, ..., 6 is Saturday
function countCertainDays( days, d0, d1 ) {
  var ndays = 1 + Math.round((d1-d0)/(24*3600*1000));
  var sum = function(a,b) {
    return a + Math.floor( ( ndays + (d0.getDay()+6-b) % 7 ) / 7 ); };
  return days.reduce(sum,0);
}

计算星期一,星期三和星期五的示例两个日期之间的1,3,5]

Example on counting Mondays, Wednesdays, and Fridays [1,3,5] between two dates:

countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,1)) // 1
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,2)) // 1
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,3)) // 2
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,4)) // 2
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,5)) // 3
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,6)) // 3
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,7)) // 3

请注意, Date 的月份参数为0,所以2014年9月1日是日期(2014,8,1)

Note that the month parameter to Date is 0-based, so 1 Sept 2014 is Date(2014,8,1).

这篇关于计算日期之间的具体工作日数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆