domingo, 19 de novembro de 2017

Calculate Last Sunday of Month In C

I have been working on a new project that will be published soon and for these project, I needed to calculate the date of the last Sunday of a given month in the current year. This was a hell of a problem because I didn't found anything useful on the Internet that could help me figure how to solve this problem. So I decided to share it with you and keep a registry with everything explained so if anybody gets stuck in the same problem than me maybe this will help. You can see the code below:

As you can see on the Gist the code is pretty simple and the whole trick for this is on line 25. The expression "((d += m < 3 ? y-- : y - 2, 23*m/9 + d + 4 + y/4- y/100 + y/400)%7) " published by Michael Keith and Tom Craver in 1990 converts a Gregorian date into a numerical day of the week and you can read about it here. The expression does preserve neither y nor d, and returns a zero-based index representing the day, starting with Sunday. For example, and as you can see in the table below if the day is Monday the expression returns 1.

Day Of Week Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Index Retured 0 1 2 3 4 5 6

Now that you know how the expression works and what it will return you, all that you need to do in order to get the date of last Sunday of the Month is calculate the Day of the Week for the last date of the Month and then subtract it to the last day of the same Month and voilá there is the date of the last Sunday.

Sem comentários:

Enviar um comentário