Wednesday, March 17, 2010

More date and day functions


#include "stdio.h"
#include "stdlib.h>"
typedef enum DayOfWeek_ {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY} DayOfWeek;

// Returns 1 for a leap year, otherwise 0
int isLeap(int year)
{
int leap = 0;
if(year % 4 == 0) {
leap = 1;
if(year % 100 == 0) {
leap = 0;
if(year % 400 == 0) {
leap = 1;
}
}
}
return leap;
}

int dateToInt(int year, int month, int dayOfMonth)
{
static int cumDaysInMonth[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
int num = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
num += cumDaysInMonth[month-1] + dayOfMonth;
if(isLeap(year) && month >= 3)
num++;
return num;
}

int diffDate(int y1, int m1, int d1, int y2, int m2, int d2)
{
int num1 = dateToInt(y1, m1, d1);
int num2 = dateToInt(y2, m2, d2);
int diff = abs(num2 - num1);
printf("Diff days (%d, %d, %d) - (%d, %d, %d) : %d\n", y1, m1, d1, y2, m2, d2, diff);
return diff;
}

char *getDayOfWeekName(int dayOfWeek)
{
switch(dayOfWeek) {
case 0: return "SUNDAY";
case 1: return "MONDAY";
case 2: return "TUEDAY";
case 3: return "WEDNESDAY";
case 4: return "THURSDAY";
case 5: return "FRIDAY";
case 6: return "SATURDAY";
}
// Error condition
return "ERROR";
}

int getDayOfWeek(int year, int month, int dayOfMonth)
{
int num = dateToInt(year, month, dayOfMonth);
int dow = num % 7;
printf("DayOfWeek (%d, %d, %d) : %s\n", year, month, dayOfMonth, getDayOfWeekName(dow));
return dow;
}

void printMonth(int year, int month)
{
static int daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static char dayChars[7] = {'N', 'M', 'T', 'W', 'H', 'F', 'S'};
int firstDow = getDayOfWeek(year, month, 1);
int i;
int dm = daysInMonth[month-1];
if(isLeap(year) && month == 2)
dm = 29;
for(i = 0; i < dm; i++)
printf("%3d", i+1);
printf("\n");
for(i = 0; i < dm; i++)
printf("%3c", dayChars[(firstDow + i) % 7]);
printf("\n");
}

int main()
{
printMonth(2010, 3);
printMonth(2000, 5);
printMonth(2203, 5);
getDayOfWeek(2010, 4, 20);
getDayOfWeek(2000, 8, 19);
getDayOfWeek(2203, 10, 5);
diffDate(2203, 11, 13, 1923, 5, 6);

return 0;
}

No comments:

Post a Comment