c_local_time_adjustor.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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: 2008-11-12 14:37:53 -0500 (Wed, 12 Nov 2008) $
  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. namespace boost {
  18. namespace date_time {
  19. //! Adjust to / from utc using the C API
  20. /*! Warning!!! This class assumes that timezone settings of the
  21. * machine are correct. This can be a very dangerous assumption.
  22. */
  23. template<class time_type>
  24. class c_local_adjustor {
  25. public:
  26. typedef typename time_type::time_duration_type time_duration_type;
  27. typedef typename time_type::date_type date_type;
  28. typedef typename date_type::duration_type date_duration_type;
  29. //! Convert a utc time to local time
  30. static time_type utc_to_local(const time_type& t)
  31. {
  32. date_type time_t_start_day(1970,1,1);
  33. time_type time_t_start_time(time_t_start_day,time_duration_type(0,0,0));
  34. if (t < time_t_start_time) {
  35. boost::throw_exception(std::out_of_range("Cannot convert dates prior to Jan 1, 1970"));
  36. BOOST_DATE_TIME_UNREACHABLE_EXPRESSION(return time_t_start_time); // should never reach
  37. }
  38. date_duration_type dd = t.date() - time_t_start_day;
  39. time_duration_type td = t.time_of_day();
  40. std::time_t t2 = dd.days()*86400 + td.hours()*3600 + td.minutes()*60 + td.seconds();
  41. std::tm tms, *tms_ptr;
  42. tms_ptr = c_time::localtime(&t2, &tms);
  43. date_type d(static_cast<unsigned short>(tms_ptr->tm_year + 1900),
  44. static_cast<unsigned short>(tms_ptr->tm_mon + 1),
  45. static_cast<unsigned short>(tms_ptr->tm_mday));
  46. time_duration_type td2(tms_ptr->tm_hour,
  47. tms_ptr->tm_min,
  48. tms_ptr->tm_sec,
  49. t.time_of_day().fractional_seconds());
  50. return time_type(d,td2);
  51. }
  52. };
  53. } } //namespace date_time
  54. #endif