0

How do I get the current time of my linux server and convert it to a given timezone (for example MST-7) in boost c++? I want that day light saving time to be calculated automatically.

If I run the following code, dst is not considered:

 boost::posix_time::ptime currentTime = boost::posix_time::second_clock::local_time();
 date today = day_clock::local_day();
 time_zone_ptr phx_tz(new posix_time_zone("MST-07:00:00"));
 local_date_time phx_departure(currentTime, phx_tz);
Shay
  • 633
  • 2
  • 11
  • 27

2 Answers2

2

The real answer to this question is: DON'T.

I'll quote my answer from Daylight saving time and time zone best practices:

  • If using C++, be sure to use a library that uses the properly implements the IANA timezone database. These include cctz, ICU, and Howard Hinnant's "tz" library.
    • Do not use Boost for time zone conversions. While its API claims to support standard IANA (aka "zoneinfo") identifiers, it crudely maps them to fixed offsets without considering the rich history of changes each zone may have had. (Also, the file has fallen out of maintenance.)

Consider that the last commit to the Boost time zone file is dated June 24, 2011, so even with the poorly designed API and implementation that they have, it doesn't even meet its own promises because it doesn't have any knowledge of time zone changes from the last 5 years!

Additionally, you really shouldn't be using POSIX time zones. They have many deficiencies and should be discouraged. See the section on POSIX time zones in the timezone tag wiki. Instead, you should use the correct IANA/Olson time zone identifier, which would be America/Denver for US Mountain time zone (with DST), or America/Phoenix for the portion of Arizona that does not use DST.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • Thanks for your replay. I am thinking of using ICU library instead of boost. Are you familiar with it? My concern is how to get automatic updates for the timezone. Do you know if its enough to update the zoneinfo directory through linux updates or do i need to update the ICU library? Does ICU load the timezones directly from /usr/share/zoneinfo ? – Shay Jan 07 '16 at 09:34
  • If you don't need localization, just tz conversions, you're probably better off with cctz or hh's lib. Not sure on your specific questions. Read the docs or try it, or ask a new question here. – Matt Johnson-Pint Jan 19 '16 at 20:30
0

You could specify the DST information in your time_zone definition:

time_zone_ptr phx_tz(new posix_time_zone("MST-07MDT01:00:00,M3.2.0/02:00:00,M11.1.0/02:00:00"));
George Houpis
  • 1,729
  • 1
  • 9
  • 5