C++ Date and Time
Introduction
C++ provides functionality for handling date and time through the `
Getting Current Date and Time with <ctime>
The `
#include <iostream>
#include <ctime>
using namespace std;
int main() {
std::time_t now = std::time(nullptr);
// Note: ctime() returns a string that ends with a newline and is not thread-safe
std::cout << "Current date and time: " << std::ctime(&now);
}
Current date and time: Tue Aug 12 16:35:22 2025
Formatted Date and Time
Use `std::localtime` to break down a `time_t` into components and `std::put_time` (in `
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int main() {
std::time_t now = std::time(nullptr);
std::tm local = *std::localtime(&now); // Not thread-safe in multithreaded code
std::cout << std::put_time(&local, "%Y-%m-%d") << '\n';
std::cout << std::put_time(&local, "%H:%M:%S") << '\n';
}
2025-08-12 16:35:22
Using <chrono> in Modern C++
The `
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
using namespace std;
using namespace std::chrono;
int main() {
auto now = system_clock::now();
std::time_t t = system_clock::to_time_t(now);
std::tm local = *std::localtime(&t);
std::cout << std::put_time(&local, "%F %T") << '\n'; // e.g., 2025-08-12 16:35:22
}
Measuring Execution Time
Use `std::chrono` and a steady clock for timing code. `steady_clock` is monotonic and not affected by system clock changes. Avoid relying on `high_resolution_clock` portability—it may alias another clock.
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
int main() {
using namespace std::chrono_literals;
auto start = steady_clock::now();
// Simulated workload
std::this_thread::sleep_for(50ms);
auto end = steady_clock::now();
auto ms = duration_cast<milliseconds>(end - start);
cout << "Execution time: " << ms.count() << " ms\n";
}
Execution time: ~50 ms
Best Practices
- Prefer `
- Use `steady_clock` for measuring durations/intervals; use `system_clock` for real-world timestamps.
- For formatted local time, use `std::put_time` with `std::localtime`; consider thread-safe variants or `
- Store timestamps in UTC (e.g., `system_clock::time_point`) and convert to local time only for display.
- Be mindful of time zones, daylight saving time transitions, and localization when formatting dates.