I tried strftime, which has %z and %Z, but these are outputs like +0800 and PST. I'd like to get the longer name like America/Los_Angeles. Is there a function call to do this?
There is not a standard way to do this until C++20, and even then only the latest MSVC has implemented it to date (gcc is getting close).
In C++20 there is a type std::chrono::time_zone
which has a member function called name()
which will return a string
such as "America/Los_Angeles".
It might be used like this:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
zoned_time local_now{"America/Los_Angeles", system_clock::now()};
cout << local_now << " " << local_now.get_time_zone()->name() << '\n';
}
Which just output for me:
2022-12-31 07:34:41.482431 PST America/Los_Angeles
Or if your computer's local time zone is currently set to "America/Los_Angeles", then the zoned_time
construction could look like this instead:
zoned_time local_now{current_zone(), system_clock::now()};
If all you want is the time zone name, and not the current time, this can be further simplified to just:
cout << current_zone()->name() << '\n';
Prior to C++20 the only way I'm aware of to get functionality like this is to use my free, open-source C++20 chrono preview library which will work with C++11/14/17.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With