Using struct tm and mktime, find the number of days from 26 January 2026 to 15 August 2026 and the weekday of the second date.
Solution
main.c
#include <math.h>
#include <stdio.h>
#include <time.h>
static time_t make_date(int y, int m, int d) {
struct tm t = {.tm_year = y - 1900, .tm_mon = m - 1, .tm_mday = d, .tm_hour = 12, .tm_isdst = -1};
return mktime(&t); /* noon avoids daylight-saving edge cases */
}
int main(void) {
static const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
time_t a = make_date(2026, 1, 26), b = make_date(2026, 8, 15);
printf("%.0f days apart\n", round(difftime(b, a) / 86400));
struct tm t = {.tm_year = 126, .tm_mon = 7, .tm_mday = 15, .tm_hour = 12, .tm_isdst = -1};
mktime(&t); /* fills in tm_wday and tm_yday */
printf("15 Aug 2026 is a %s, day %d of the year\n", days[t.tm_wday], t.tm_yday + 1);
return 0;
}
Output Verified by compiling and running
201 days apart
15 Aug 2026 is a Saturday, day 227 of the year
mktime normalises a struct tm and computes the weekday and day of the year. Subtracting with difftime and rounding to whole days handles any one-hour daylight-saving difference.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!