You can read more about the function used for checking if the given year is a leap year by reading this article: Leap year checking algorithm in C
You can find the function that does the opposite conversion by reading Finding day of the year given the date in C
/* * Description: * Computes and returns the date * Parameters: * day - the day of the year * year - the year * Returns: * date - the corresponding date */ char *DayToDate(int day, int year) { int noDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};//number of days of each month int days[12];//each of its elements represents the number of days of the first i months int isLeapYear = 0, i = 0, d = 0; char *date; date = (char*)malloc(sizeof(char)*30); isLeapYear = LeapYear(year);//checking if the year is a leap year if(isLeapYear == 1) { noDays[1] = 29; } if(day>31)//the day is not in January { for(i=0; i<12 && count<day; i++) { if(i == 0) { days[0] = noDays[0]; } else { days[i] = days[i-1] + noDays[i]; } } d = day - days[i-2]; itoa(d,date,10); switch(i) { case 2: strcat(date," February"); break; case 3: strcat(date," March"); break; case 4: strcat(date," April"); break; case 5: strcat(date," May"); break; case 6: strcat(date," June"); break; case 7: strcat(date," July"); break; case 8: strcat(date," August"); break; case 9: strcat(date," September"); break; case 10: strcat(date," October"); break; case 11: strcat(date," November"); break; case 12: strcat(date," December"); break; } } else//the day is in January { itoa(day,date,10); strcat(date," January"); } return date; }
Example:
This C program takes a year and the day of the year and, using the function defined above, prints the corresponding date.
#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<string.h> int LeapYear(int year); char *DayToDate(int day, int year); int main(void) { int year = 0, day = 0; char *date; date = (char*)malloc(sizeof(char)*6); printf("\n Enter the year: "); scanf("%d",&year); printf(" Enter the day of year: "); scanf("%d",&day); date = DayToDate(day,year); printf("\n\tThe date is: %s",date); getch(); return 0; }
Output:
The 68th day of 2012 is the 8th of March.
No comments:
Post a Comment