conversion.hpp 2.0 KB

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