ex_seconds_since_epoch.xml 2.6 KB

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