userver: userver/utils/datetime/date.hpp Source File
Loading...
Searching...
No Matches
date.hpp
Go to the documentation of this file.
1#pragma once
2
5
6#include <chrono>
7#include <compare>
8#include <iosfwd>
9#include <stdexcept>
10#include <string>
11
13
14USERVER_NAMESPACE_BEGIN
15
16namespace logging {
17class LogHelper;
18}
19
21namespace utils::datetime {
22
29class Date final {
30public:
31 using Days = std::chrono::duration<long long, std::ratio<86400>>;
32 using SysDays = std::chrono::time_point<std::chrono::system_clock, Days>;
33
34 Date() = default;
35 Date(const Date&) noexcept = default;
36 Date& operator=(const Date&) noexcept = default;
37
39 Date(int year, int month, int day);
40
42 constexpr Date(SysDays tp) noexcept : sys_days_(tp) {}
43
48 constexpr SysDays GetSysDays() const { return sys_days_; }
49
51 constexpr explicit operator SysDays() const { return sys_days_; }
52
53 constexpr auto operator<=>(const Date&) const = default;
54
55private:
56 SysDays sys_days_{};
57};
58
60Date DateFromRFC3339String(const std::string& date_string);
61
63std::string ToString(Date date);
64
65template <formats::common::IsFormatValue Value>
66Date Parse(const Value& value, formats::parse::To<Date>) {
67 std::string str;
68 try {
69 str = value.template As<std::string>();
70 } catch (const std::exception& e) {
71 throw typename Value::ParseException("Only strings can be parsed as `utils::datetime::Date`");
72 }
73
74 try {
76 } catch (const std::exception& e) {
77 throw typename Value::ParseException("'" + str + "' cannot be parsed to `utils::datetime::Date`");
78 }
79}
80
81template <formats::common::IsFormatValue Value>
82Value Serialize(Date date, formats::serialize::To<Value>) {
83 return typename Value::Builder(ToString(date)).ExtractValue();
84}
85
86template <typename StringBuilder>
87void WriteToStream(Date value, StringBuilder& sw) {
88 WriteToStream(ToString(value), sw);
89}
90
91template <typename LogHelper = USERVER_NAMESPACE::logging::LogHelper>
92USERVER_NAMESPACE::logging::LogHelper& operator<<(USERVER_NAMESPACE::logging::LogHelper& lh, const Date& date) {
93 static_assert(
94 std::is_same_v<LogHelper, USERVER_NAMESPACE::logging::LogHelper>,
95 "This was made template to work well with forward declared "
96 "logging::LogHelper"
97 );
98 return static_cast<LogHelper&>(lh) << ToString(date);
99}
100
101std::ostream& operator<<(std::ostream& os, Date date);
102
103} // namespace utils::datetime
104
105USERVER_NAMESPACE_END