Tuesday, March 16, 2010

Converting a date to dayOfWeek

Here is the full code in C


#include "stdio.h"

typedef enum DayOfWeek_ {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY} DayOfWeek;

// month is 1 to 12
int getDayOfWeek(int year, int month, int dayOfMonth)
{
int m[12] = {4, 0, 0, 3, 5, 1, 3, 6,2, 4, 0, 2};
int dayOfWeek = ((year-1) * 5 / 4 - 5) + m[month-1] + dayOfMonth;
int leap = 0;

if(year % 4 == 0) {
leap = 1;
if(year % 100 == 0) {
leap = 0;
if(year % 400 == 0) {
leap = 1;
}
}
}
if(leap && month >= 3)
dayOfWeek++;

return (dayOfWeek % 7);
}

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";
}
//
return "ERROR";
}

int main()
{
printf("dayOfWeek(2000, 3, 17)=%s\n", getDayOfWeekName(getDayOfWeek(2000, 3, 17)));
printf("dayOfWeek(2000, 1, 15)=%s\n", getDayOfWeekName(getDayOfWeek(2000, 1, 15)));
printf("dayOfWeek(2010, 3, 17)=%s\n", getDayOfWeekName(getDayOfWeek(2010, 3, 17)));

return 0;
}




Enjoy

No comments:

Post a Comment