seconds_since_epoch.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #include "boost/date_time/local_time/local_time.hpp"
  15. #include <iostream>
  16. int main()
  17. {
  18. using namespace boost::gregorian;
  19. using namespace boost::local_time;
  20. using namespace boost::posix_time;
  21. tz_database tz_db;
  22. try {
  23. tz_db.load_from_file("../data/date_time_zonespec.csv");
  24. }catch(const data_not_accessible& dna) {
  25. std::cerr << "Error with time zone data file: " << dna.what() << std::endl;
  26. exit(EXIT_FAILURE);
  27. }catch(const bad_field_count& bfc) {
  28. std::cerr << "Error with time zone data file: " << bfc.what() << std::endl;
  29. exit(EXIT_FAILURE);
  30. }
  31. time_zone_ptr nyc_tz = tz_db.time_zone_from_region("America/New_York");
  32. date in_date(2004,10,04);
  33. time_duration td(12,14,32);
  34. // construct with local time value
  35. // create not-a-date-time if invalid (eg: in dst transition)
  36. local_date_time nyc_time(in_date,
  37. td,
  38. nyc_tz,
  39. local_date_time::NOT_DATE_TIME_ON_ERROR);
  40. std::cout << nyc_time << std::endl;
  41. ptime time_t_epoch(date(1970,1,1));
  42. std::cout << time_t_epoch << std::endl;
  43. // first convert nyc_time to utc via the utc_time()
  44. // call and subtract the ptime.
  45. time_duration diff = nyc_time.utc_time() - time_t_epoch;
  46. //Expected 1096906472
  47. std::cout << "Seconds diff: " << diff.total_seconds() << std::endl;
  48. }
  49. /* Copyright 2005: CrystalClear Software, Inc
  50. * http://www.crystalclearsoftware.com
  51. *
  52. * Subject to the Boost Software License, Version 1.0.
  53. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  54. */