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 Helpers for C++20 calendar.
5/// @ingroup userver_universal
6
7#include <chrono>
8#include <ratio>
9
10#include <userver/utils/assert.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace utils::datetime {
15
16// TODO: remove the following aliases
17using Days = std::chrono::days;
18using DaysTimepoint = std::chrono::sys_days;
19
20/// @brief Calculates the number of days between January 1, 00:00 of two years accounting for leap years.
21constexpr std::chrono::days DaysBetweenYears(int from, int to) {
22 return std::chrono::duration_cast<Days>(
23 DaysTimepoint{std::chrono::year_month_day(std::chrono::year(to), std::chrono::month(1), std::chrono::day(1))} -
24 DaysTimepoint{std::chrono::year_month_day(std::chrono::year(from), std::chrono::month(1), std::chrono::day(1))}
25 );
26}
27
28/// @brief Get the number of days in the given month of a given year.
29constexpr std::chrono::day DaysInMonth(int month, int year) {
30 UINVARIANT(month >= 1 && month <= 12, "Month must be between 1 and 12");
31 return std::chrono::year_month_day_last(
32 std::chrono::year(year),
33 std::chrono::month_day_last(std::chrono::month(month))
34 )
35 .day();
36}
37
38} // namespace utils::datetime
39
40USERVER_NAMESPACE_END