1 <?xml version=
"1.0" encoding=
"utf-8"?>
2 <!DOCTYPE library PUBLIC
"-//Boost//DTD BoostBook XML V1.0//EN"
3 "../../../tools/boostbook/dtd/boostbook.dtd">
5 <!-- Copyright (c) 2001-2005 CrystalClear Software, Inc.
6 Subject to the Boost Software License, Version 1.0.
7 (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
10 <section id=
"date_time.examples.seconds_since_epoch">
11 <title>Seconds Since Epoch
</title>
14 Example of calculating seconds elapsed since epoch (
1970-Jan-
1) using local_date_time.
18 /* This example demonstrates the use of the time zone database and
19 * local time to calculate the number of seconds since the UTC
20 * time_t epoch
1970-
01-
01 00:
00:
00. Note that the selected timezone
21 * could be any timezone supported in the time zone database file which
22 * can be modified and updated as needed by the user.
24 * To solve this problem the following steps are required:
25 *
1) Get a timezone from the tz database for the local time
26 *
2) Construct a local time using the timezone
27 *
3) Construct a posix_time::ptime for the time_t epoch time
28 *
4) Convert the local_time to utc and subtract the epoch time
32 #include
"boost/date_time/local_time/local_time.hpp"
37 using namespace boost::gregorian;
38 using namespace boost::local_time;
39 using namespace boost::posix_time;
43 tz_db.load_from_file(
"../data/date_time_zonespec.csv");
44 }catch(data_not_accessible dna) {
45 std::cerr <<
"Error with time zone data file: " << dna.what() << std::endl;
47 }catch(bad_field_count bfc) {
48 std::cerr <<
"Error with time zone data file: " << bfc.what() << std::endl;
52 time_zone_ptr nyc_tz = tz_db.time_zone_from_region(
"America/New_York");
53 date in_date(
2004,
10,
04);
54 time_duration td(
12,
14,
32);
55 // construct with local time value
56 // create not-a-date-time if invalid (eg: in dst transition)
57 local_date_time nyc_time(in_date,
60 local_date_time::NOT_DATE_TIME_ON_ERROR);
62 std::cout << nyc_time << std::endl;
64 ptime time_t_epoch(date(
1970,
1,
1));
65 std::cout << time_t_epoch << std::endl;
67 // first convert nyc_time to utc via the utc_time()
68 // call and subtract the ptime.
69 time_duration diff = nyc_time.utc_time() - time_t_epoch;
72 std::cout <<
"Seconds diff: " << diff.total_seconds() << std::endl;