November 2005
Beginner to intermediate
594 pages
16h 23m
English
You want to convert the current time from one time zone to another.
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 <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/local_time_adjustor.hpp>
using namespace std;
using namespace boost::gregorian;
using namespace boost::date_time;
using namespace boost::posix_time;
typedef local_adjustor<ptime, -5, us_dst> EasternTZ;
typedef local_adjustor<ptime, -7, no_dst> 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
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 ...