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:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int y, m, d;
//number of days of each month
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
//choose the year that you want
int year = 2017;
//checking if february has 28 or 29 days
days[1] -= (y % 4) || (!(y % 100) && (y % 400));
//goes through every month
for(m = 1; m <= 12; ++m){
//get the number of days from the array for the corresponding month
d = days[m - 1];
y = year;
//expression for converting a Gregorian date into a numerical day of the week
int day = days[m-1] - ((d += m < 3 ? y-- : y - 2, 23*m/9 + d + 4 + y/4- y/100 + y/400)%7);
//print the date of the month that is the last Sunday
printf("%d - %d - %d\n", day, m, year);
}
return 0;
}
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.
Previous How Setup Arduino IDE for NodeMCU(ESP8266) Next Programming ESP8266 (ESP-01) USING A UART ESP-01 - Part 1

Sem comentários:

Enviar um comentário