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
14/// @brief Date, time-of-day, clocks, and parsing utilities.
15namespace utils::datetime {
16
17// TODO: remove the following aliases
18using Days = std::chrono::days;
19using DaysTimepoint = std::chrono::sys_days;
20
21/// @brief Calculates the number of days between January 1, 00:00 of two years accounting for leap years.
22constexpr std::chrono::days DaysBetweenYears(int from, int to) {
23 return std::chrono::duration_cast<Days>(
24 DaysTimepoint{std::chrono::year_month_day(std::chrono::year(to), std::chrono::month(1), std::chrono::day(1))} -
25 DaysTimepoint{std::chrono::year_month_day(std::chrono::year(from), std::chrono::month(1), std::chrono::day(1))}
26 );
27}
28
29/// @brief Get the number of days in the given month of a given year.
30constexpr std::chrono::day DaysInMonth(int month, int year) {
31 UINVARIANT(month >= 1 && month <= 12, "Month must be between 1 and 12");
32 return std::chrono::year_month_day_last(
33 std::chrono::year(year),
34 std::chrono::month_day_last(std::chrono::month(month))
35 )
36 .day();
37}
38
39} // namespace utils::datetime
40
41USERVER_NAMESPACE_END