C Date Representation

Handling Dates in C: struct tm

Unlike 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.


1. The struct tm Structure

The 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_mon starts at 0 (January = 0, December = 11), and tm_year is the number of years since 1900. To get the current year, you must add 1900 to tm_year.


2. Formatting Dates with strftime

Once 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.

Formatting Current Date

#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; }


Common strftime Format Codes:


3. Creating a Custom Date

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.

Creating a Specific Date

#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; }


Exercise

?

In the struct tm structure, what integer value represents the month of January?