Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

How to count specific days of the week between two dates in 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);
}

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...