conversion.hpp 2.1 KB

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