#include <iostream>
#include <ctime>
#include <iomanip>
/*
You can format dates in C++ using either the classic C‑style strftime()
or the modern C++20 <chrono> formatting.
*/
/*
Useful format codes:
%Y — 4‑digit year
%m — month (01–12)
%d — day of month
%H — hour (00–23)
%I — hour (01–12)
%M — minutes
%S — seconds
%A — full weekday name
%B — full month name
%c — locale’s default date/time
%j — day of year (001–366)
%W — week number (Mon-start)
%U — week number (Sun-start)
*/
int main() {
time_t now = time(nullptr); // Current timestamp
tm* t = localtime(&now); // Break into components
char buf[128] = "";
// --- Basic numeric formats ---
strftime(buf, sizeof(buf), "%Y-%m-%d", t);
std::cout << "[ISO 8601] YYYY-MM-DD: " << buf << "\n";
strftime(buf, sizeof(buf), "%d/%m/%Y", t);
std::cout << "[European] DD/MM/YYYY: " << buf << "\n";
strftime(buf, sizeof(buf), "%m-%d-%Y", t);
std::cout << "[US] MM-DD-YYYY: " << buf << "\n";
// --- Time formats ---
strftime(buf, sizeof(buf), "%H:%M:%S", t);
std::cout << "[24-hour] HH:MM:SS: " << buf << "\n";
strftime(buf, sizeof(buf), "%I:%M:%S %p", t);
std::cout << "[12-hour] HH:MM:SS AM/PM: " << buf << "\n";
// --- Full date with names ---
strftime(buf, sizeof(buf), "%A, %B %d, %Y", t);
std::cout << "Full weekday + month name: " << buf << "\n";
strftime(buf, sizeof(buf), "%a, %b %d", t);
std::cout << "Short weekday + month name: " << buf << "\n";
// --- Combined date/time ---
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", t);
std::cout << "Full timestamp: " << buf << "\n";
strftime(buf, sizeof(buf), "%c", t);
std::cout << "Locale default date/time: " << buf << "\n";
// --- Special formats ---
strftime(buf, sizeof(buf), "Day of year: %j", t);
std::cout << buf << "\n";
strftime(buf, sizeof(buf), "Week number (Mon-start): %W", t);
std::cout << buf << "\n";
strftime(buf, sizeof(buf), "Week number (Sun-start): %U", t);
std::cout << buf << "\n";
}
/*
run:
[ISO 8601] YYYY-MM-DD: 2026-05-20
[European] DD/MM/YYYY: 20/05/2026
[US] MM-DD-YYYY: 05-20-2026
[24-hour] HH:MM:SS: 09:17:23
[12-hour] HH:MM:SS AM/PM: 09:17:23 AM
Full weekday + month name: Wednesday, May 20, 2026
Short weekday + month name: Wed, May 20
Full timestamp: 2026-05-20 09:17:23
Locale default date/time: Wed May 20 09:17:23 2026
Day of year: 140
Week number (Mon-start): 20
Week number (Sun-start): 20
*/