userver: userver/utils/datetime/cpp_20_calendar.hpp Source File
Loading...
Searching...
No Matches
cpp_20_calendar.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/datetime/cpp_20_calendar.hpp
4/// @brief This file brings date.h into utils::datetime::date namespace,
5/// which is std::chrono::operator/ (calendar) in c++20.
6/// @ingroup userver_universal
7
8// TODO : replace with C++20 std::chrono:: when time comes
9
10#include <chrono>
11#include <ratio>
12
13#include <date/date.h>
14
15#include <userver/utils/assert.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace utils::datetime {
20
21namespace date = ::date;
22
23using Days = date::days;
24using DaysTimepoint = date::sys_days;
25
26/// @brief Calculates the number of days between January 1, 00:00 of two years accounting for leap years.
27constexpr Days DaysBetweenYears(int from, int to) {
28 return std::chrono::duration_cast<Days>(
29 DaysTimepoint{date::year_month_day(date::year(to), date::month(1), date::day(1))} -
30 DaysTimepoint{date::year_month_day(date::year(from), date::month(1), date::day(1))}
31 );
32}
33
34/// @brief Get the number of days in the given month of a given year.
35constexpr date::day DaysInMonth(int month, int year) {
36 UINVARIANT(month >= 1 && month <= 12, "Month must be between 1 and 12");
37 return date::year_month_day_last(date::year(year), date::month_day_last(date::month(month))).day();
38}
39
40} // namespace utils::datetime
41
42USERVER_NAMESPACE_END