Code Examples In C++
Introduction
Managing date, time, and time zones is a fundamental aspect of many software applications, including logging, scheduling, and timestamping.
The Standard Template Library (STL) and additional libraries like <chrono>, <ctime>, and third-party solutions such as Boost.DateTime provide powerful tools to manage time-related data
Get Current Time
In C++, retrieving the current time is a common task for many applications. The C++ Standard Library provides robust tools to handle time and date functionality through the <chrono> and <ctime> headers.
The <chrono> library, introduced in C++11, offers a modern and type-safe way to work with time, while <ctime> provides a traditional, C-style approach for handling time and dates. Each method has its use cases, depending on your specific needs.
Method:
1// compatibility with C APIs
2std::time(time_t *const _Time)
3
4// for higher precision
5std::chrono::system_clock::now()
Example:
1#include <iostream>
2#include <ctime>
3#include <chrono>
4#include <iomanip>
5
6int main() {
7 // Get the current time
8 std::time_t current_time = std::time(nullptr);
9
10 // Convert to local time and print
11 std::cout << "Current time using ctime: " << std::ctime(¤t_time);
12
13 // Use chrono
14 // Get current time
15 auto now = std::chrono::system_clock::now();
16
17 // Convert to time_t
18 auto current_time_chrono = std::chrono::system_clock::to_time_t(now);
19
20 // Get milliseconds
21 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
22 now.time_since_epoch()) % 1000;
23
24 // Format and print
25 std::cout << "Current time using chrono: "
26 << std::put_time(std::localtime(¤t_time_chrono), "%Y-%m-%d %H:%M:%S")
27 << '.' << std::setfill('0') << std::setw(3) << ms.count()
28 << std::endl;
29
30 return 0;
31}
Result:
1Current time using ctime: Mon Dec 9 23:00:42 2024
2Current time using chrono: 2024-12-09 23:00:42.881
Get Unix Timestamp
Unix timestamps are a standard way of representing time as the number of seconds (or milliseconds) elapsed since the Unix epoch, which is January 1, 1970, at 00:00:00 UTC. They are widely used in web development for logging, scheduling, and synchronizing time across systems due to their simplicity and consistency.
In C++, obtaining a Unix timestamp is straightforward using the tools provided in the Standard Library. Modern C++ (C++11 and later) introduced the <chrono> library, which offers precise and type-safe utilities for working with time and dates. Additionally, the traditional <ctime> library, inherited from C, can also be used to retrieve and manipulate Unix timestamps.
Method:
1// compatibility with C APIs
2std::time(time_t *const _Time)
3
4// for higher precision
5std::chrono::time_point<Clock,Duration>::time_since_epoch()
Example:
1#include <iostream>
2#include <chrono>
3#include <ctime>
4
5int main() {
6 // Using ctime
7 // Get the current time as a Unix timestamp
8 std::time_t unix_timestamp = std::time(nullptr);
9
10 // Print the Unix timestamp
11 std::cout << "Unix timestamp: " << unix_timestamp << std::endl;
12
13 // Using chrono
14 // Get the current time_point
15 auto now = std::chrono::system_clock::now();
16
17 // Calculate the Unix timestamp in milliseconds
18 auto milliseconds_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(
19 now.time_since_epoch()
20 ).count();
21
22 // Print the Unix timestamp
23 std::cout << "Unix timestamp (milliseconds): " << milliseconds_since_epoch << std::endl;
24
25 return 0;
26}
Result:
1Unix timestamp: 1733757082
2Unix timestamp (milliseconds): 1733757082726
Construct New Time
Creating and manipulating date-time objects is a fundamental part of many programming tasks
Modern C++ (C++11 and later) introduced the <chrono> library, which provides a robust and type-safe framework for working with time points, durations, and clocks. Additionally, the traditional <ctime> library offers basic utilities to manage date-time values, often using structs like std::tm.
Method:
1// compatibility with C APIs
2mktime(struct tm *const _Tm)
3
4// Use chrono
5std::chrono::system_clock::from_time_t(std::time_t t)
Example:
1#include <iostream>
2#include <ctime>
3#include <chrono>
4
5int main() {
6 // Specify a custom time
7 std::tm custom_time = {};
8 custom_time.tm_year = 2024 - 1900; // Year since 1900
9 custom_time.tm_mon = 6; // Month (0 = January, 6 = July)
10 custom_time.tm_mday = 15; // Day of the month
11 custom_time.tm_hour = 8; // Hour (0-23)
12 custom_time.tm_min = 45; // Minute (0-59)
13 custom_time.tm_sec = 30; // Second (0-59)
14
15 // Convert to time_t
16 std::time_t timestamp = std::mktime(&custom_time);
17 std::cout << "Unix timestamp using mktime: " << timestamp << std::endl;
18
19 // Convert to std::chrono::time_point
20 auto time_point = std::chrono::system_clock::from_time_t(timestamp);
21 // Print the time in seconds since epoch
22 std::cout << "Unix timestamp using chrono: "
23 << std::chrono::duration_cast<std::chrono::seconds>(time_point.time_since_epoch()).count()
24 << std::endl;
25
26 return 0;
27}
Result:
1Unix timestamp using mktime: 1721004330
2Unix timestamp using chrono: 1721004330
Convert Unix timestamp to Readable Date Time
Unix timestamps, which count the number of seconds since January 1, 1970 (UTC), are a widely used format for storing and processing time. However, in most real-world applications, it is necessary to convert these timestamps into a human-readable date-time format for display, logging, or debugging purposes.
In C++, you can achieve this conversion using tools from the Standard Library. Both the modern <chrono> library, introduced in C++11, and the traditional <ctime> library provide mechanisms for working with timestamps and formatting them into readable strings.
Method:
1// compatibility with C APIs
2std::localtime(const std::time_t* time)
3std::asctime( const std::tm* time_ptr)
4
5// Use chrono
6std::chrono::system_clock::from_time_t(std::time_t t)
Example:
1#include <iostream>
2#include <ctime>
3#include <chrono>
4#include <iomanip> // for std::put_time
5
6int main() {
7 // Example Unix timestamp
8 std::time_t unix_timestamp = 1712000000; // Replace with your timestamp
9
10 // Convert to tm struct for local time
11 std::tm *tm_time = std::localtime(&unix_timestamp);
12
13 // Print the human-readable date and time
14 std::cout << "Readable date and time using std::localtime: "
15 << std::asctime(tm_time);
16
17 // Convert Unix timestamp to a time_point
18 auto time_point = std::chrono::system_clock::from_time_t(unix_timestamp);
19
20 // Convert to time_t to use with std::localtime
21 std::time_t time = std::chrono::system_clock::to_time_t(time_point);
22
23 // Convert to tm structure for formatting
24 std::tm *tm_time_chrono = std::localtime(&time);
25
26 // Print the human-readable date and time
27 std::cout << "Readable date and time using chrono: "
28 << std::put_time(tm_time_chrono, "%Y-%m-%d %H:%M:%S") << std::endl;
29
30 return 0;
31}
Result:
1Readable date and time using std::localtime: Tue Apr 2 03:33:20 2024
2Readable date and time using chrono: 2024-04-02 03:33:20
Convert Date Time to Unix timestamp
In many applications, it is necessary to convert a specified date and time into a Unix timestamp. This conversion is essential for tasks such as storing dates in databases, performing time calculations, or working with APIs that use Unix timestamps.
In C++, you can convert a date-time into a Unix timestamp using tools from the Standard Library. Both the modern <chrono> library (introduced in C++11) and the traditional <ctime> library provide functionality for handling this conversion.
Method:
1// compatibility with C APIs
2mktime(struct tm *const _Tm)
3
4// Use chrono
5std::chrono::system_clock::from_time_t(std::time_t t)
Example:
1#include <iostream>
2#include <ctime>
3#include <chrono>
4
5int main() {
6 // Specify a custom time
7 std::tm custom_time = {};
8 custom_time.tm_year = 2024 - 1900; // Year since 1900
9 custom_time.tm_mon = 6; // Month (0 = January, 6 = July)
10 custom_time.tm_mday = 15; // Day of the month
11 custom_time.tm_hour = 8; // Hour (0-23)
12 custom_time.tm_min = 45; // Minute (0-59)
13 custom_time.tm_sec = 30; // Second (0-59)
14
15 // Convert to time_t
16 std::time_t timestamp = std::mktime(&custom_time);
17 std::cout << "Unix timestamp using mktime: " << timestamp << std::endl;
18
19 // Convert to std::chrono::time_point
20 auto time_point = std::chrono::system_clock::from_time_t(timestamp);
21 // Print the time in seconds since epoch
22 std::cout << "Unix timestamp using chrono: "
23 << std::chrono::duration_cast<std::chrono::seconds>(time_point.time_since_epoch()).count()
24 << std::endl;
25
26 return 0;
27}
Result:
1Unix timestamp using mktime: 1721004330
2Unix timestamp using chrono: 1721004330
Change Time Zone
Timezones play a critical role in applications that work with global users or time-sensitive data across different regions.
C++ provides tools to work with time zones, primarily through the <chrono> library (enhanced in C++20) and external libraries
Method:
1// calc time zone offset manually
2std::localtime(const std::time_t* time)
3
4// Use chrono
5std::chrono::system_clock::from_time_t(std::time_t t)
Example:
1#include <iostream>
2#include <ctime>
3#include <iomanip>
4#include <chrono>
5
6int main() {
7 // Input: UTC date-time
8 std::tm utcTm = {};
9 utcTm.tm_year = 2024 - 1900; // Year since 1900
10 utcTm.tm_mon = 11; // Month (0-based, so December is 11)
11 utcTm.tm_mday = 10; // Day of the month
12 utcTm.tm_hour = 14; // Hour (24-hour format)
13 utcTm.tm_min = 30; // Minute
14 utcTm.tm_sec = 0; // Second
15
16 // Convert to time_t
17 std::time_t utcTime = std::mktime(&utcTm);
18
19 if (utcTime == -1) {
20 std::cerr << "Error: Failed to convert UTC time.\n";
21 return 1;
22 }
23
24 std::cout << "UTC Time: " << std::put_time(&utcTm, "%Y-%m-%d %H:%M:%S") << '\n';
25
26 // Define a fixed time zone offset (e.g., UTC+5:30)
27 const int offsetHours = 5;
28 const int offsetMinutes = 30;
29
30 // Adjust time for the time zone
31 std::time_t localTime = utcTime + (offsetHours * 3600) + (offsetMinutes * 60);
32
33 // Convert back to std::tm
34 std::tm* localTm = std::localtime(&localTime);
35
36 // Output the local time
37 std::cout << "Local Time (UTC+5:30) using localtime: " << std::put_time(localTm, "%Y-%m-%d %H:%M:%S") << '\n';
38
39 // Using chrono
40 // Calculate offset in seconds
41 std::chrono::seconds offset = std::chrono::hours(offsetHours) + std::chrono::minutes(offsetMinutes);
42 // Convert to local time with offset
43 auto utcTimePoint = std::chrono::system_clock::from_time_t(utcTime);
44 auto localTimePoint = utcTimePoint + offset;
45
46 // Convert local time_point back to time_t for output
47 std::time_t localTime_chrono = std::chrono::system_clock::to_time_t(localTimePoint);
48 std::tm* localTm_chrono = std::localtime(&localTime_chrono);
49
50 // Output local time
51 std::cout << "Local Time (UTC+5:30) using chrono: " << std::put_time(localTm_chrono, "%Y-%m-%d %H:%M:%S") << '\n';
52
53 return 0;
54}
Result:
1UTC Time: 2024-12-10 14:30:00
2Local Time (UTC+5:30) using localtime: 2024-12-10 20:00:00
3Local Time (UTC+5:30) using chrono: 2024-12-10 20:00:00
Time Addition and Subtraction
Performing arithmetic operations like addition and subtraction on date and time is a common requirement in programming. These operations are useful for tasks such as scheduling events, calculating durations, and determining deadlines.
In C++, The <chrono> library offers a type-safe and intuitive way to perform date-time arithmetic using time points, durations, and clocks. Additionally, the traditional <ctime> library can handle basic operations with date-time values represented by the std::tm structure.
Method:
1// using std::tm directly
2std::tm
3
4// Measure High-Precision Execution Time
5std::chrono::high_resolution_clock::now();
Example:
1#include <iostream>
2#include <ctime>
3#include <iomanip>
4#include <chrono>
5#include <thread>
6
7int main() {
8 // Define a specific date-time (e.g., 2024-12-10 14:30:00)
9 std::tm timeStruct = {};
10 timeStruct.tm_year = 2024 - 1900; // Year since 1900
11 timeStruct.tm_mon = 11; // Month (0-based, December is 11)
12 timeStruct.tm_mday = 10; // Day of the month
13 timeStruct.tm_hour = 14; // Hour (24-hour format)
14 timeStruct.tm_min = 30; // Minute
15 timeStruct.tm_sec = 0; // Second
16
17 // Add days, hours, and minutes
18 int daysToAdd = 5; // Add 5 days
19 int hoursToAdd = 10; // Add 10 hours
20 int minutesToAdd = 90; // Add 90 minutes
21
22 // Perform arithmetic
23 timeStruct.tm_mday += daysToAdd; // Add days
24 timeStruct.tm_hour += hoursToAdd; // Add hours
25 timeStruct.tm_min += minutesToAdd; // Add minutes
26
27 // Normalize the date and time
28 std::time_t normalizedTime = std::mktime(&timeStruct);
29 if (normalizedTime == -1) {
30 std::cerr << "Failed to normalize the time.\n";
31 return 1;
32 }
33
34 // Convert back to std::tm for display
35 std::tm* resultTime = std::localtime(&normalizedTime);
36
37 // Display the resulting date-time
38 std::cout << "Original Time: 2024-12-10 14:30:00\n";
39 std::cout << "Updated Time: " << std::put_time(resultTime, "%Y-%m-%d %H:%M:%S") << '\n';
40
41 // Measure the time cost
42 auto start = std::chrono::high_resolution_clock::now();
43
44 // Simulate some work (e.g., sleeping for 100 milliseconds)
45 std::this_thread::sleep_for(std::chrono::milliseconds(100));
46
47 // Stop the timer
48 auto end = std::chrono::high_resolution_clock::now();
49
50 // Calculate the duration
51 auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
52
53 // Output the time taken in nanoseconds
54 std::cout << "Time taken: " << duration.count() << " nanoseconds.\n";
55
56 return 0;
57}
Result:
1Original Time: 2024-12-10 14:30:00
2Updated Time: 2024-12-16 02:00:00
3Time taken: 100054713 nanoseconds.
Pause or sleep for a specific time
Pausing or delaying the execution of a program is a common requirement in various applications, such as implementing retries, creating animations, scheduling tasks, or rate-limiting requests.
With the introduction of the <chrono> library in C++11, programmers gained access to a type-safe and intuitive way to define and control durations. The <thread> library, also introduced in C++11, provides the std::this_thread::sleep_for and std::this_thread::sleep_until functions, which work seamlessly with <chrono> durations. Additionally, traditional methods such as std::this_thread::sleep (C++11) and platform-specific functions like sleep() (on POSIX) or Sleep() (on Windows) are also available.
Method:
1// recommended for C++ 11 or later
2std::this_thread::sleep_for
3
4// Before C++ 11
5// POSIX-compliant systems, like Linux and macOS
6#include <unistd.h>
7sleep(unsigned int seconds);
8
9// #include <time.h>
10nanosleep(const struct timespec *duration, struct timespec *_Nullable rem);
11
12// Windows
13// #include <windows.h>
14Sleep(unsigned long dwMilliseconds);
Example:
1#include <iostream>
2#include <chrono>
3#include <thread>
4
5int main() {
6 std::cout << "Sleeping for 500 milliseconds...\n";
7
8 // Sleep for 500 milliseconds
9 std::this_thread::sleep_for(std::chrono::milliseconds(500));
10
11 std::cout << "Awoke after 500 milliseconds!\n";
12 return 0;
13}
Result:
1Sleeping for 500 milliseconds...
2Awoke after 500 milliseconds!