Date and Time in C++

Date and time is typically done using the <chrono> library for durations and time points, and <ctime> for functions related to C-style time manipulation.
Necessary headers for working with date and time.

#include <iostream>
#include <chrono>
#include <ctime>

System Clock and Time Point

Using std::chrono::system_clock for working with the system clock, and std::chrono::time_point to represent points in time.

using namespace std::chrono;
auto now = system_clock::now();
time_point<system_clock> tp = system_clock::to_time_t(now);

Conversion to Calendar Time

Conversion from a time_point to calendar time using std::ctime or std::localtime.

std::cout << "Current time: " << std::ctime(&tp) << std::endl;

Duration

Using std::chrono::duration to represent time durations.

auto duration = now.time_since_epoch();
std::cout << "Duration since epoch: " << duration.count() << " ticks." << std::endl;

Formatting Output

Using std::put_time to format time output.

std::time_t t = system_clock::to_time_t(now);
std::cout << "Formatted time: " << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S") << std::endl;

Sleep for a Duration

Pausing execution for a certain duration using std::this_thread::sleep_for.

std::this_thread::sleep_for(std::chrono::seconds(2));

Parse Time from Strings

Parsing time from a string using std::get_time.

std::tm tm = {};
std::istringstream ss("2022-01-30 12:34:56");
ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
auto parsed_time = system_clock::from_time_t(std::mktime(&tm));

Calculate Elapsed Time

Calculating the elapsed time between two points.

auto start = high_resolution_clock::now();
// Code to measure
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
std::cout << "Elapsed time: " << duration.count() << " milliseconds." << std::endl;

Working with Time Zones (Optional)

Time zones, consider external libraries like tz or other third-party solutions.

// Example using the "tz" library
#include <date/tz.h>

auto now = date::make_zoned(date::current_zone(), system_clock::now()); Adjust these definitions based on your specific requirements. The C++ <chrono> and <ctime> libraries offer various functionalities for working with dates and times