How do I format dates and times?

In C++, you can format dates and times using the strftime function from the ctime library. This allows you to convert time values into formatted strings. Here's a simple example to illustrate how this can be achieved:

#include <iostream> #include <iomanip> #include <ctime> int main() { std::time_t now = std::time(0); // Get current time std::tm *ltm = std::localtime(&now); // Convert to local time // Format and display the date and time std::cout << "Year: " << 1900 + ltm->tm_year << std::endl; std::cout << "Month: " << 1 + ltm->tm_mon << std::endl; std::cout << "Day: " << ltm->tm_mday << std::endl; std::cout << "Time: " << ltm->tm_hour << ":" << ltm->tm_min << ":" << ltm->tm_sec << std::endl; return 0; }

C++ date formatting time formatting strftime ctime library current time