Getting the current time of another time zone using C ++

How to get the current time of another time zone? For example, I need to know the current time in Singapore, where, when my system is set to PT.

+4
source share
4 answers

One implementation would be to use time to get the current time in UTC, and then control the TZ environment variable in your destination time zone. Then use localtime_r to convert to this time in local time.

+3
source

A new answer to a very old question.

Given the C ++ 11 or C ++ 14 compiler and this time zone library , the current time in Singapore is:

 #include "tz.h" #include <iostream> int main() { using namespace std::chrono; std::cout << date::make_zoned("Asia/Singapore", system_clock::now()) << '\n'; } 

which just outputs for me:

 2015-08-19 05:25:05.453824 SGT 

It shows the current local date, time, and abbreviation. And it is based on the <chrono> library and IANA time zone database .

std::chrono::system_clock::now() returns the timestamp in the UTC time zone. This program finds the time zone information for "Asia / Singapore" and translates the UTC timestamp into a pair representing the local time and current time zone for this location.

The above program does not depend on the current time zone of the computer.

+6
source

Use UTC (GMT) as much as possible.

If you need to (for example) print a report that will be in a different time zone, use something like SystemTimeToTzSpecificLocalTime () to localize it.

+1
source

You can convert to GMT and then convert to any time zone that you want.

0
source

All Articles