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 ?
Asked
Active
Viewed 136 times
0
-
Use formulas found in [Wikipedia article about Julian Day Number](https://en.m.wikipedia.org/wiki/Julian_day). – pmg Apr 26 '20 at 12:49
-
This may help: [ISO 8601 week number in C](https://stackoverflow.com/q/42568215/2410359) – chux - Reinstate Monica Apr 26 '20 at 22:10
2 Answers
1
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");
}
}

Lefix
- 55
- 7
0
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.

Chrissu
- 382
- 1
- 13
-
1What you say is true, but I consider the calendar in which days can start from Tuesday or the others. I mean, in that case it won't be true. – Apr 26 '20 at 13:09
-
You are right, I didn't think that fully through. :D It's a bit more complex... Check this one out: https://stackoverflow.com/questions/274861/how-do-i-calculate-the-week-number-given-a-date – Chrissu Apr 26 '20 at 13:16