date.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // Copyright (c) 2019-2023 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_MYSQL_IMPL_DATE_HPP
  8. #define BOOST_MYSQL_IMPL_DATE_HPP
  9. #pragma once
  10. #include <boost/mysql/date.hpp>
  11. #include <cstdio>
  12. #include <ostream>
  13. #include <stdexcept>
  14. BOOST_CXX14_CONSTEXPR boost::mysql::date::date(time_point tp)
  15. {
  16. bool ok = detail::days_to_ymd(tp.time_since_epoch().count(), year_, month_, day_);
  17. if (!ok)
  18. throw std::out_of_range("date::date: time_point was out of range");
  19. }
  20. BOOST_CXX14_CONSTEXPR boost::mysql::date::time_point boost::mysql::date::get_time_point() const noexcept
  21. {
  22. assert(valid());
  23. return unch_get_time_point();
  24. }
  25. BOOST_CXX14_CONSTEXPR boost::mysql::date::time_point boost::mysql::date::as_time_point() const
  26. {
  27. if (!valid())
  28. throw std::invalid_argument("date::as_time_point: invalid date");
  29. return unch_get_time_point();
  30. }
  31. constexpr bool boost::mysql::date::operator==(const date& rhs) const noexcept
  32. {
  33. return year_ == rhs.year_ && month_ == rhs.month_ && day_ == rhs.day_;
  34. }
  35. BOOST_CXX14_CONSTEXPR boost::mysql::date::time_point boost::mysql::date::unch_get_time_point() const noexcept
  36. {
  37. return time_point(days(detail::ymd_to_days(year_, month_, day_)));
  38. }
  39. std::ostream& boost::mysql::operator<<(std::ostream& os, const date& value)
  40. {
  41. // Worst-case output is 14 chars, extra space just in case
  42. char buffer[32]{};
  43. snprintf(
  44. buffer,
  45. sizeof(buffer),
  46. "%04u-%02u-%02u",
  47. static_cast<unsigned>(value.year()),
  48. static_cast<unsigned>(value.month()),
  49. static_cast<unsigned>(value.day())
  50. );
  51. os << buffer;
  52. return os;
  53. }
  54. #endif