YouTip LogoYouTip

Cpp Date Time

# C++ Date and Time Guide The C++ standard library does not provide a dedicated, built-in date type. Instead, C++ inherits the structures and functions for date and time manipulation from the C standard library. To use these date and time-related functions and structures in your C++ program, you need to include the `` header file. --- ## Core Concepts and Data Types There are four primary time-related data types defined in ``: * `clock_t`: Used to represent processor time (clock ticks). * `time_t`: Used to represent calendar time, typically as the number of seconds elapsed since the Unix Epoch (00:00:00 UTC, January 1, 1970). * `size_t`: A standard unsigned integer type used for sizes and counts (e.g., returned by formatting functions). * `tm`: A structure that holds calendar date and time components broken down into individual members. ### The `tm` Structure The `tm` structure is crucial for date and time manipulation. It stores calendar components in a structured C-style format. Its definition is as follows: ```cpp struct tm { int tm_sec; // Seconds: normally 0 to 59, but can be up to 61 to allow for leap seconds int tm_min; // Minutes: 0 to 59 int tm_hour; // Hours: 0 to 23 int tm_mday; // Day of the month: 1 to 31 int tm_mon; // Month: 0 to 11 (Note: January is 0) int tm_year; // Year: Number of years since 1900 int tm_wday; // Day of the week: 0 to 6 (Sunday is 0) int tm_yday; // Day of the year: 0 to 365 (January 1st is 0) int tm_isdst; // Daylight Saving Time flag: positive if DST is in effect, // 0 if not, and negative if information is unavailable }; ``` --- ## Essential Date and Time Functions The following table lists the standard functions available in `` for managing dates and times: | No. | Function & Description | | :--- | :--- | | 1 | **`time_t time(time_t *time);`**
Returns the current calendar time of the system as the number of seconds elapsed since January 1, 1970. If the system has no time source, it returns `-1`. If a non-null pointer is passed, the return value is also stored in the pointed object. | | 2 | **`char *ctime(const time_t *time);`**
Returns a pointer to a string representing the local time based on the `time_t` value. The format is:
`Www Mmm dd hh:mm:ss yyyy\n\0`
Where:
  • `Www`: Day of the week (e.g., Tue)
  • `Mmm`: Month (e.g., Jul)
  • `dd`: Day of the month (e.g., 29)
  • `hh:mm:ss`: 24-hour time
  • `yyyy`: Year (e.g., 2025)
Example output: `"Tue Jul 29 19:12:15 2025\n\0"` | | 3 | **`struct tm *localtime(const time_t *time);`**
Converts a `time_t` value to a pointer to a `tm` structure representing the local time. | | 4 | **`clock_t clock(void);`**
Returns the processor time consumed by the program since it started. Returns `-1` if the processor time is not available. | | 5 | **`char *asctime(const struct tm *time);`**
Converts the broken-down time in the `tm` structure into a human-readable string format: `Www Mmm dd hh:mm:ss yyyy\n\0`. | | 6 | **`struct tm *gmtime(const time_t *time);`**
Converts a `time_t` value to a pointer to a `tm` structure representing Coordinated Universal Time (UTC) / Greenwich Mean Time (GMT). | | 7 | **`time_t mktime(struct tm *time);`**
Converts a broken-down local time in a `tm` structure into a calendar time (`time_t`) value. It also normalizes the fields of the `tm` structure. | | 8 | **`double difftime(time_t time2, time_t time1);`**
Calculates the difference in seconds between `time2` and `time1` (`time2 - time1`). | | 9 | **`size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);`**
Formats the date and time from a `tm` structure into a custom string format based on the specified format specifiers. | --- ## Code Examples ### 1. Getting the Current Date and Time The following example demonstrates how to retrieve the current system date and time, displaying both the local time and the Coordinated Universal Time (UTC). ```cpp #include #include using namespace std; int main() { // Get the current system calendar time time_t now = time(0); // Convert 'now' to a human-readable string format (Local Time) char* dt = ctime(&now); cout << "Local Date and Time: " << dt; // Convert 'now' to a tm structure representing UTC tm *gmtm = gmtime(&now); dt = asctime(gmtm); cout << "UTC Date and Time: " << dt; return 0; } ``` **Example Output:** ```text Local Date and Time: Sat Jan 8 20:07:41 2011 UTC Date and Time: Sun Jan 9 03:07:41 2011 ``` --- ### 2. Formatting Time Using the `tm` Structure The `tm` structure allows you to extract and format individual components of a date and time. When working with `tm`, remember to use the member access operator `->` when dealing with pointers. ```cpp #include #include using namespace std; int main() { // Get the current system calendar time time_t now = time(0); cout << "Seconds elapsed since Jan 1, 1970: " << now << endl; // Convert to local time structure tm *ltm = localtime(&now); // Output individual components of the tm structure // Note: tm_year is years since 1900, tm_mon is 0-indexed (0-11) cout << "Year: " << 1900 + ltm->tm_year << endl; cout << "Month: " << 1 + ltm->tm_mon << endl; cout << "Day: " << ltm->tm_mday << endl; cout << "Time: " << ltm->tm_hour << ":" << ltm->tm_min << ":" << ltm->tm_sec << endl; return 0; } ``` **Example Output:** ```text Seconds elapsed since Jan 1, 1970: 1503564157 Year: 2017 Month: 8 Day: 24 Time: 16:42:37 ``` --- ## Important Considerations 1. **Year Offset (`tm_year`)**: The `tm_year` field stores the number of years **since 1900**. To display the actual calendar year, you must add `1900` to this value (e.g., `1900 + ltm->tm_year`). 2. **Month Indexing (`tm_mon`)**: The `tm_mon` field is 0-indexed, meaning January is represented by `0` and December by `11`. To display the month in standard 1-12 format, you must add `1` (e.g., `1 + ltm->tm_mon`). 3. **Thread Safety**: Standard functions like `localtime`, `gmtime`, and `ctime` return pointers to static internal buffers. Calling these functions from multiple threads or repeatedly in the same thread can overwrite previous results. For thread-safe operations, modern platforms provide alternatives like `localtime_r` (POSIX) or `localtime_s` (Windows). 4. **Modern C++ Alternative**: For C++11 and newer, consider using the `` library. It provides a type-safe, robust, and high-resolution alternative for handling durations, time points, and clocks.
← Cpp Increment Decrement OperatCpp References β†’