struct tmUnlike modern, higher-level programming languages that provide built-in Date objects, C relies on the <time.h> library to manage calendar dates. Understanding how C structures and manipulates date information is essential for developing applications involving scheduling, logging, or database management.
At the heart of date manipulation in C is the struct tm structure.
struct tm StructureThe struct tm is a data structure defined in <time.h> that breaks down calendar time into readable, human-friendly components like year, month, and day.
Here is a simplified look at the members of struct tm:
struct tm {
int tm_sec; // Seconds [0, 60] (60 is for leap seconds)
int tm_min; // Minutes [0, 59]
int tm_hour; // Hours [0, 23]
int tm_mday; // Day of the month [1, 31]
int tm_mon; // Months since January [0, 11] (Note: January is 0)
int tm_year; // Years since 1900 (Note: 2024 is represented as 124)
int tm_wday; // Days since Sunday [0, 6]
int tm_yday; // Days since January 1 [0, 365]
int tm_isdst; // Daylight Saving Time flag
};
Crucial Pitfalls: Notice that
tm_monstarts at 0 (January = 0, December = 11), andtm_yearis the number of years since 1900. To get the current year, you must add 1900 totm_year.
strftimeOnce you have a populated struct tm, you will likely want to display it as a string. The strftime() function allows you to format dates and times beautifully, similar to how printf formats numbers.
#include <stdio.h> #include <time.h>int main() { time_t rawtime; struct tm *info; char buffer[80]; // Get current Unix time time(&rawtime); // Convert to local time structure info = localtime(&rawtime); // Format the date: "YYYY-MM-DD" strftime(buffer, sizeof(buffer), "%Y-%m-%d", info); printf("Formatted Date: %s\n", buffer); // Format the date: "Weekday, Month Day, Year" strftime(buffer, sizeof(buffer), "%A, %B %d, %Y", info); printf("Long Form Date: %s\n", buffer); return 0; }
strftime Format Codes:%Y: Four-digit year (e.g., 2025)%m: Two-digit month (01-12)%d: Two-digit day of the month (01-31)%A: Full weekday name (e.g., Friday)%B: Full month name (e.g., October)You can manually populate a struct tm to represent a specific date in history or the future. You can then use the mktime() function to validate it and convert it back to a standard time_t timestamp.
#include <stdio.h> #include <time.h>int main() { struct tm custom_date = {0}; // Initialize to 0 // Setting the date to July 20, 1969 (Moon Landing) custom_date.tm_year = 1969 - 1900; // Years since 1900 custom_date.tm_mon = 7 - 1; // Months since January (0-11) custom_date.tm_mday = 20; // Day of the month // mktime automatically figures out the day of the week (tm_wday) mktime(&custom_date); char buffer[80]; strftime(buffer, sizeof(buffer), "%A", &custom_date); printf("July 20, 1969 was a %s.\n", buffer); return 0; }
In the struct tm structure, what integer value represents the month of January?