Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

5.4. 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 <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

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page