aboutsummaryrefslogtreecommitdiff
path: root/5.9.c
blob: e768bd57581cc4d98eb74314fc412123d543550a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#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;
}