Reputation: 693
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);
Upvotes: 0
Views: 770
Reputation: 241485
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.
Upvotes: 2
Reputation: 1729
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"));
Upvotes: 0