Converting Between Time Zones

Problem

You want to convert the current time from one time zone to another.

Solution

To convert between time zones, use the time zone conversion routines from the Boost date_time library. Example 5-8 shows how to finds the time in Tucson, Arizona given a time in New York City.

Example 5-8. Converting between time zones

#include #include #include #include using namespace std; using namespace boost::gregorian; using namespace boost::date_time; using namespace boost::posix_time; typedef local_adjustor EasternTZ; typedef local_adjustor ArizonaTZ; ptime NYtoAZ(ptime nytime) { ptime utctime = EasternTZ::local_to_utc(nytime); return ArizonaTZ::utc_to_local(utctime); } int main( ) { // May 1st 2004, boost::gregorian::date thedate(2004, 6, 1); ptime nytime(thedate, hours(19)); // 7 pm ptime aztime = NYtoAZ(nytime); cout << "On May 1st, 2004, when it was " << nytime.time_of_day( ).hours( ); cout << ":00 in New York, it was " << aztime.time_of_day( ).hours( ); cout << ":00 in Arizona " << endl; }

The program in Example 5-8 outputs the following:

On May 1st, 2004, when it was 19:00 in New York, it was 16:00 in Arizona

 

Discussion

The time zone conversions in Example 5-8 goes through a two-step process. First, I convert the time to UTC, and then convert the UTC time to the second time zone. Note that the time zones in the Boost date_time library are represented as types using the local_adjustor template class. Each type has conversion functions to convert from the given time zone to UTC (the local_to_utc function), and to convert from UTC to the given time zone (the utc_to_local function).

Категории