Reputation:
I wrote a code for printing calendar according to Gregorian calendar. But I have a problem, I need to calculate the current number of week in order to print my calendar with help of array[5][7]. I need formula or program to find number of week for ex. year:2020 month:4 day:26 and I should find number of week and it's 4. is there any formula ?
Upvotes: 0
Views: 175
Reputation: 55
You have to know the day of week first!
For this use Gauss's algorithm Kraitchik's variation:
https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
dayofweek(y, m, d) /* 1 <= m <= 12, y > 1752 (in the U.K.) */
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
int k = (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
return k == 0 ? 6 : (k-1); // This will return 0 for monday...6 for sunday
}
Then, your week number will be shifted regarding first day of month:
w = (d - 1 + dayofweek(y, m, 1))/7 + 1;
here a code sample working for me:
#include <stdio.h>
#include <stdint.h>
static const int days[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static const char* dayofws[] = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};
static int dayofweek(int y, int m, int d) /* 1 <= m <= 12, y > 1752 (in the U.K.) */
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
int k = (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
return k == 0 ? 6 : (k-1); // This will return 0 for monday...6 for sunday
}
void main (void)
{
int y = 2020;
for (int m = 1; m <= 12; m++)
{
for (int d = 1; d <= days[m]; d++)
{
int w = (d - 1 + dayofweek(y, m, 1))/7 + 1;
printf("%d ", dayofweek(y, m, 1));
printf("%d/%02d/%02d : %d (%s)\n", y, m, d, w, dayofws[dayofweek(y, m, d)]);
}
printf("\n");
}
}
Upvotes: 1
Reputation: 417
Can't you just get the number of days since January 1st, divide this number by 7 and add 1 (so it starts with week 1 and not 0) For example:
January 17th: 17 / 7 = 2 -> 2+1 = Week 3
For the 7th, 14th, 21st, 28th etc day, you could check the remainder. If remainder is 0, week should be week-1. So day 14 is week 2 and not week 3.
Upvotes: 0