Følgende kode:
#include <time.h>
#include <stdio.h>
#define MINUTE (60)
#define HOUR (MINUTE * 60)
#define DAY (HOUR * 24)
char * DAYS[] = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
char * MONTHS[] = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
int main (int argc, char ** argv) {
time_t t;
struct tm tim;
int i;
/* First find current month and year and other stuff */
time(&t);
localtime_r(&t, &tim);
/* Now change the tm struct to reflect the first day of this month */
tim.tm_mday = 1;
t = mktime(&tim);
/* Now write all first days of each month for 12 months */
for (i = 0; i < 12; i++) {
localtime_r(&t, &tim);
printf("First day of %s in year %d is %s\\n", MONTHS[tim.tm_mon], 1900 + tim.tm_year, DAYS[tim.tm_wday]);
/* Add 31 days to the time and find first day of that month */
t += (DAY * 31);
localtime_r(&t, &tim);
tim.tm_mday = 1;
t = mktime(&tim);
}
return 0;
}
...giver følgende output:
First day of September in year 2006 is Friday
First day of October in year 2006 is Sunday
First day of November in year 2006 is Wednesday
First day of December in year 2006 is Friday
First day of January in year 2007 is Monday
First day of February in year 2007 is Thursday
First day of March in year 2007 is Thursday
First day of April in year 2007 is Sunday
First day of May in year 2007 is Tuesday
First day of June in year 2007 is Friday
First day of July in year 2007 is Sunday
First day of August in year 2007 is Wednesday