Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current time zone?

In most of the examples I had seen:

time_zone_ptr zone( new posix_time_zone("MST-07") );  

But I just want to get the current time zone for the machine that runs the code. I do not want to hard code the time zone name.

like image 222
Cheok Yan Cheng Avatar asked Jan 26 '10 01:01

Cheok Yan Cheng


People also ask

How do I get the current time zone in Python?

You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.

What timezone is datetime NOW ()?

The property UtcNow of the DateTime class returns the current date and time of the machine running the code, expressed in UTC format. UTC is a universal format to represent date and time as an alternative to local time. Also known as the GMT+00 timezone.

How do I get current ZonedDateTime?

now() now() method of a ZonedDateTime class used to obtain the current date-time from the system clock in the default time-zone. This method will return ZonedDateTime based on system clock with default time-zone to obtain the current date-time. The zone and offset will be set based on the time-zone in the clock.


1 Answers

Plain posix: call tzset, use tzname.

#include <ctime> tzset(); time_zone_ptr zone(new posix_time_zone(tzname[localtime(0)->tm_isdst])); 

Posix with glibc/bsd additions:

time_zone_ptr zone(new posix_time_zone(localtime(0)->tm_zone)); 

The above are abbreviated Posix timezones, defined in terms of offset from UTC and not stable over time (there's a longer form that can include DST transitions, but not political and historical transitions).

ICU is portable and has logic for retrieving the system timezone as an Olson timezone (snippet by sumwale):

// Link with LDLIBS=`pkg-config icu-i18n --libs` #include <unicode/timezone.h> #include <iostream>  using namespace U_ICU_NAMESPACE;  int main() {   TimeZone* tz = TimeZone::createDefault();   UnicodeString us;   std::string s;    tz->getID(us);   us.toUTF8String(s);   std::cout << "Current timezone ID: " << s << '\n';   delete tz; } 

On Linux, ICU is implemented to be compatible with tzset and looks at TZ and /etc/localtime, which on recent Linux systems is specced to be a symlink containing the Olson identifier (here's the history). See uprv_tzname for implementation details.

Boost doesn't know how to use the Olson identifier. You could build a posix_time_zone using the non-DST and DST offsets, but at this point, it's best to keep using the ICU implementation. See this Boost FAQ.

like image 167
Tobu Avatar answered Sep 29 '22 04:09

Tobu