简体   繁体   English

查找给定月份的第一天的星期几

[英]Find a day of week for given first day in month

How could be calculated a day of the week if we know the day number of the first day in month? 如果我们知道一个月第一天的星期几,该如何计算星期几? Lets say we have 1..7 days in a week I want to get number of the 4th day in the month if the 1st = 5 (Friday) then result should be 1 (Monday). 假设我们一周中有1..7天,如果第一天= 5(星期五),那么我想获取每月第4天的数字,那么结果应为1(星期一)。

1st - 5 Friday
2nd - 6 Saturday
3rd - 7 Sunday
4th - 1 Monday

(a=4, b=5) = 1 (a = 4,b = 5)= 1

I tried to calculate the common formula: 我试图计算通用公式:

result = (a + b - 1) % 7 

So it works for all cases except the case when a = 3, 10, 17, 24, 31, because result = 0, but should be 7. How can it be fixed to get this formula work for all days? 因此,它适用于所有情况,但结果a = 3、10、17、24、31的情况除外,因为结果= 0,但应为7。如何固定该公式使它在整天都有效?

You need to avoid the result zero. 您需要避免结果为零。 Here is one way: 这是一种方法:

result = (a + b - 2) % 7 + 1

You subtract one more from your sum, to allow zero and work on the previous day, then you take the remainder modulo 7 to get the day which can include zero, then add one to get to the day wanted and avoid zero. 您从总和中减去一个,以允许为零并在前一天工作,然后将余数取模7以得到可以包括零的那一天,然后加一以得到想要的那一天并避免为零。 Note that the order of operations will do the modulus before adding one. 请注意,运算顺序在加一之前会做模。 If you want to make that more explicit, you could use 如果您想使其更明确,可以使用

result = ((a + b - 2) % 7) + 1

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

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