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