Samuel van der Veen
Samuel van der Veen

Reputation: 1

Getting time in a different time zone using C++

C++ will let me get the local time with std::localtime(), but that presents a problem when I'm using an online compiler whose server is in a different continent. How do I get the time in PST instead of "local" time?

Here's the code I'm using:

#include <ctime>
#include <iostream>

int main()
{
  time_t secSinceEpoch = time(0);
  tm* timeStruct = std::localtime(&secSinceEpoch);
  int hour = timeStruct->tm_hour;
  int min = timeStruct->tm_min;

  std::cout << "Time in California is " << hour << ":" << min << std::endl;

  return 0;
}

How to I manipulate localtime() so it returns the time in Los Angeles, rather than in India where the online server is?

Upvotes: 0

Views: 45

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 219325

This can not portably be done in C++ prior to C++20.1

In C++20 it is:

#include <chrono>
#include <format>
#include <iostream>

int main()
{
  std::chrono::zoned_time zt{"America/Los_Angeles", std::chrono::system_clock::now()};
  std::cout << "Time in California is " << std::format("{:%H:%M}", zt) << '\n';
}

Demo.

Example output:

Time in California is 13:22

zoned_time is a pairing of a time_zone const* and a system_clock-based time_point. When formatting it will use the time_zone to translate the sys_time into local_time and format that. The time_zone can be assigned via an IANA time zone name.

If you instead want the computer's current local time, then simply replace "America/Los_Angeles" with std::chrono::current_zone().


1 Technically that is an exaggeration. It can be done. But it is so hard to do that it is not a practical answer to the question. To do it one has to build a parser to the IANA timezone database and use that to transform system_clock::time_point into any local time in the IANA database. And then figure out how to format that local time_point. Here is an example library that did just that: https://github.com/HowardHinnant/date. This is the library that became the C++20 solution as described in this answer.

Upvotes: 1

Related Questions