1 | #ifndef _GREGORIAN__CONVERSION_HPP___ |
---|---|
2 | #define _GREGORIAN__CONVERSION_HPP___ |
3 | |
4 | /* Copyright (c) 2004-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 | #include <cstring> |
13 | #include <string> |
14 | #include <stdexcept> |
15 | #include <boost/throw_exception.hpp> |
16 | #include <boost/date_time/c_time.hpp> |
17 | #include <boost/date_time/special_defs.hpp> |
18 | #include <boost/date_time/gregorian/gregorian_types.hpp> |
19 | |
20 | namespace boost { |
21 | |
22 | namespace gregorian { |
23 | |
24 | //! Converts a date to a tm struct. Throws out_of_range exception if date is a special value |
25 | inline |
26 | std::tm to_tm(const date& d) |
27 | { |
28 | if (d.is_special()) |
29 | { |
30 | std::string s = "tm unable to handle "; |
31 | switch (d.as_special()) |
32 | { |
33 | case date_time::not_a_date_time: |
34 | s += "not-a-date-time value"; break; |
35 | case date_time::neg_infin: |
36 | s += "-infinity date value"; break; |
37 | case date_time::pos_infin: |
38 | s += "+infinity date value"; break; |
39 | default: |
40 | s += "a special date value"; break; |
41 | } |
42 | boost::throw_exception(std::out_of_range(s)); |
43 | } |
44 | |
45 | std::tm datetm; |
46 | std::memset(&datetm, 0, sizeof(datetm)); |
47 | boost::gregorian::date::ymd_type ymd = d.year_month_day(); |
48 | datetm.tm_year = ymd.year - 1900; |
49 | datetm.tm_mon = ymd.month - 1; |
50 | datetm.tm_mday = ymd.day; |
51 | datetm.tm_wday = d.day_of_week(); |
52 | datetm.tm_yday = d.day_of_year() - 1; |
53 | datetm.tm_isdst = -1; // negative because not enough info to set tm_isdst |
54 | return datetm; |
55 | } |
56 | |
57 | //! Converts a tm structure into a date dropping the any time values. |
58 | inline |
59 | date date_from_tm(const std::tm& datetm) |
60 | { |
61 | return date(static_cast<unsigned short>(datetm.tm_year+1900), |
62 | static_cast<unsigned short>(datetm.tm_mon+1), |
63 | static_cast<unsigned short>(datetm.tm_mday)); |
64 | } |
65 | |
66 | } } //namespace boost::gregorian |
67 | |
68 | #endif |
69 |