c_local_time_adjustor.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef DATE_TIME_C_LOCAL_TIME_ADJUSTOR_HPP__
  2. #define DATE_TIME_C_LOCAL_TIME_ADJUSTOR_HPP__
  3. /* Copyright (c) 2002,2003,2005 CrystalClear Software, Inc.
  4. * Use, modification and distribution is subject to the
  5. * Boost Software License, Version 1.0. (See accompanying
  6. * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  7. * Author: Jeff Garland, Bart Garst
  8. * $Date$
  9. */
  10. /*! @file c_local_time_adjustor.hpp
  11. Time adjustment calculations based on machine
  12. */
  13. #include <stdexcept>
  14. #include <boost/throw_exception.hpp>
  15. #include <boost/date_time/compiler_config.hpp>
  16. #include <boost/date_time/c_time.hpp>
  17. #include <boost/numeric/conversion/cast.hpp>
  18. namespace boost {
  19. namespace date_time {
  20. //! Adjust to / from utc using the C API
  21. /*! Warning!!! This class assumes that timezone settings of the
  22. * machine are correct. This can be a very dangerous assumption.
  23. */
  24. template<class time_type>
  25. class c_local_adjustor {
  26. public:
  27. typedef typename time_type::time_duration_type time_duration_type;
  28. typedef typename time_type::date_type date_type;
  29. typedef typename date_type::duration_type date_duration_type;
  30. //! Convert a utc time to local time
  31. static time_type utc_to_local(const time_type& t)
  32. {
  33. date_type time_t_start_day(1970,1,1);
  34. time_type time_t_start_time(time_t_start_day,time_duration_type(0,0,0));
  35. if (t < time_t_start_time) {
  36. boost::throw_exception(std::out_of_range("Cannot convert dates prior to Jan 1, 1970"));
  37. BOOST_DATE_TIME_UNREACHABLE_EXPRESSION(return time_t_start_time); // should never reach
  38. }
  39. date_duration_type dd = t.date() - time_t_start_day;
  40. time_duration_type td = t.time_of_day();
  41. uint64_t t2 = static_cast<uint64_t>(dd.days())*86400 +
  42. static_cast<uint64_t>(td.hours())*3600 +
  43. static_cast<uint64_t>(td.minutes())*60 +
  44. td.seconds();
  45. // detect y2038 issue and throw instead of proceed with bad time
  46. std::time_t tv = boost::numeric_cast<std::time_t>(t2);
  47. std::tm tms, *tms_ptr;
  48. tms_ptr = c_time::localtime(&tv, &tms);
  49. date_type d(static_cast<unsigned short>(tms_ptr->tm_year + 1900),
  50. static_cast<unsigned short>(tms_ptr->tm_mon + 1),
  51. static_cast<unsigned short>(tms_ptr->tm_mday));
  52. time_duration_type td2(tms_ptr->tm_hour,
  53. tms_ptr->tm_min,
  54. tms_ptr->tm_sec,
  55. t.time_of_day().fractional_seconds());
  56. return time_type(d,td2);
  57. }
  58. };
  59. } } //namespace date_time
  60. #endif