Home > Software design >  How to generate current datetime with system's regional format in C ?
How to generate current datetime with system's regional format in C ?

Time:02-17

I'm looking for a way to get the current system date time formatted in a manner consistent with the system's region.

For example, a system in the US would have something like: 01-31-2022 1:59:00 PM

And a system in Europe would have something like: 31-01-2022 13:59:00

I've experimented a bit with using Boost but can't seem to get exactly what I'm specifying here; is there any library or implementation that might let me achieve this? Thanks.

CodePudding user response:

You need to query for timezone, and then use a format specifier when you output the timestamp. See the comment for %c in https://man7.org/linux/man-pages/man3/strftime.3.html, and also https://man7.org/linux/man-pages/man3/tzset.3.html. As for linking, it's part of libc so adding -lc to your compiler invocation should be sufficient

CodePudding user response:

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:

#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).

  • Related