#include <stdio.h>
#define LEAP_YEAR_DAYS 366
#define NON_LEAP_YEAR_DAYS 365
#define NO_OF_MONTHS 12
int year_day(int day, int month, int year);
void month_day(int *day, int *month, int year, int year_day_val);
int
main(void)
{
int day, month, year, year_day_val;
year = 2020;
printf("yd: %d\n", (year_day_val = year_day(15, 2, year)));
month_day(&day, &month, year, year_day_val);
printf("md: %d-%d\n", day, month);
}
static char daytab[][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
int
year_day(int day, int month, int year)
{
int i, leap;
leap = ((!year%4 && year%100 ) || !year%400);
if (month > NO_OF_MONTHS || day > daytab[leap][month-1])
return -1;
for (i = 0, --month; i < month; i++)
day += daytab[leap][i];
return day;
}
void
month_day(int *day, int *month, int year, int year_day_val)
{
int i, leap;
leap = ((!year%4 && year%100 ) || !year%400);
if ((leap && year_day_val > LEAP_YEAR_DAYS) || (!leap && year_day_val > NON_LEAP_YEAR_DAYS)) {
*month = -1;
*day = -1;
return;
}
for (i = 1; year_day_val > daytab[leap][i-1]; i++)
year_day_val -= daytab[leap][i-1];
*month = i;
*day = year_day_val;
return;
}