Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get current time zone city name like America/Los_Angeles

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading