First, we configure the locale for the user's default by imbuing the output stream with the empty-name locale (locale("")
). Then we use the locale-dependent date and time formats with std::put_time
. For example: Live On Coliru
#include <ctime>
#include <iomanip>
#include <iostream>
int main() {
std::time_t raw_now = time(nullptr);
std::tm now = *localtime(&raw_now);
std::cout.imbue(std::locale(""));
std::cout << std::put_time(&now, "My locale: %x %X\n");
// For comparison, how we'd expect it to show up for a
// user configured for Great Britain:
std::cout.imbue(std::locale("en_GB.UTF-8"));
std::cout << std::put_time(&now, "Great Britain: %x %X\n");
}
On my box (configured for the US), this produces the following output:
My locale: 02/16/2022 06:05:48 PM
Great Britain: 16/02/22 18:05:48
There is also a %c
format to produce date and time, but this (at least normally) includes the day of the week (e.g., Wed 16 Feb 2022 18:11:53 PST
) which doesn't fit with what you seem to want.
As a side-note: all compilers are supposed to accept at least "C"
and ""
for locale names. Any other name (like the en_GB.UTF-8
I've used above) depends on the compiler. You may need a different string if you're using a different compiler (I was testing with g++ on Linux).