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