Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

linux

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?

like image 458
thang Avatar asked Sep 10 '25 18:09

thang


1 Answers

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.

like image 155
Howard Hinnant Avatar answered Sep 13 '25 07:09

Howard Hinnant