Imported Upstream version 1.72.0
[platform/upstream/boost.git] / libs / date_time / example / local_time / seconds_since_epoch.cpp
1 /* This example demonstrates the use of the time zone database and 
2  * local time to calculate the number of seconds since the UTC
3  * time_t epoch 1970-01-01 00:00:00.  Note that the selected timezone
4  * could be any timezone supported in the time zone database file which
5  * can be modified and updated as needed by the user.
6  *
7  * To solve this problem the following steps are required:
8  * 1) Get a timezone from the tz database for the local time
9  * 2) Construct a local time using the timezone
10  * 3) Construct a posix_time::ptime for the time_t epoch time
11  * 4) Convert the local_time to utc and subtract the epoch time
12  * 
13  */
14
15 #include "boost/date_time/local_time/local_time.hpp"
16 #include <iostream>
17
18 int main()
19 {
20   using namespace boost::gregorian; 
21   using namespace boost::local_time;
22   using namespace boost::posix_time;
23   
24   tz_database tz_db;
25   try {
26     tz_db.load_from_file("../data/date_time_zonespec.csv");
27   }catch(const data_not_accessible& dna) {
28     std::cerr << "Error with time zone data file: " << dna.what() << std::endl;
29     exit(EXIT_FAILURE);
30   }catch(const bad_field_count& bfc) {
31     std::cerr << "Error with time zone data file: " << bfc.what() << std::endl;
32     exit(EXIT_FAILURE);
33   }
34
35   time_zone_ptr nyc_tz = tz_db.time_zone_from_region("America/New_York");
36   date in_date(2004,10,04);
37   time_duration td(12,14,32);
38   // construct with local time value
39   // create not-a-date-time if invalid (eg: in dst transition)
40   local_date_time nyc_time(in_date, 
41                            td, 
42                            nyc_tz, 
43                            local_date_time::NOT_DATE_TIME_ON_ERROR);
44
45   std::cout << nyc_time << std::endl;
46
47   ptime time_t_epoch(date(1970,1,1)); 
48   std::cout << time_t_epoch << std::endl;
49
50   // first convert nyc_time to utc via the utc_time() 
51   // call and subtract the ptime.
52   time_duration diff = nyc_time.utc_time() - time_t_epoch;
53
54   //Expected 1096906472
55   std::cout << "Seconds diff: " << diff.total_seconds() << std::endl;
56
57 }
58
59
60 /*  Copyright 2005: CrystalClear Software, Inc
61  *  http://www.crystalclearsoftware.com
62  *
63  *  Subject to the Boost Software License, Version 1.0.
64  * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
65  */