Time Shield Library 2.0.0
C++ library for working with time
Loading...
Searching...
No Matches
time_zone_offset_conversions.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#pragma once
3#ifndef TIME_SHIELD_HEADER_CONVERSIONS_TIME_ZONE_OFFSET_CONVERSIONS_HPP_INCLUDED
4#define TIME_SHIELD_HEADER_CONVERSIONS_TIME_ZONE_OFFSET_CONVERSIONS_HPP_INCLUDED
5
8
10
11namespace time_shield {
12
15
21 template<class T = TimeZoneStruct>
22 inline T to_time_zone(tz_t offset) {
23 const int64_t off = static_cast<int64_t>(offset);
24 const int64_t abs_val = (off < 0) ? -off : off;
25
26 T tz;
27 tz.hour = static_cast<decltype(tz.hour)>(abs_val / static_cast<int64_t>(SEC_PER_HOUR));
28 tz.min = static_cast<decltype(tz.min)>(
29 (abs_val % static_cast<int64_t>(SEC_PER_HOUR)) / static_cast<int64_t>(SEC_PER_MIN)
30 );
31 tz.is_positive = (off >= 0);
32 return tz;
33 }
34
37 template<class T>
38 TIME_SHIELD_CONSTEXPR inline tz_t to_tz_offset(const T& tz) noexcept {
39 const int sign = tz.is_positive ? 1 : -1;
40 const int64_t sec = static_cast<int64_t>(tz.hour) * SEC_PER_HOUR
41 + static_cast<int64_t>(tz.min) * SEC_PER_MIN;
42 return static_cast<tz_t>(sign * sec);
43 }
44
48 TIME_SHIELD_CONSTEXPR inline tz_t tz_offset_hm(int hour, int min = 0) noexcept {
49 const int sign = (hour < 0) ? -1 : 1;
50 const int64_t ah = (hour < 0) ? -static_cast<int64_t>(hour) : static_cast<int64_t>(hour);
51 const int64_t am = (min < 0) ? -static_cast<int64_t>(min) : static_cast<int64_t>(min);
52 return static_cast<tz_t>(sign * (ah * SEC_PER_HOUR + am * SEC_PER_MIN));
53 }
54
57 TIME_SHIELD_CONSTEXPR inline bool is_valid_tz_offset(tz_t off) noexcept {
58 // conservative range: [-12:00, +14:00]
59 return off % 60 == 0
60 && off >= -12 * SEC_PER_HOUR
61 && off <= 14 * SEC_PER_HOUR;
62 }
63
65
66}; // namespace time_shield
67
68#endif // TIME_SHIELD_HEADER_CONVERSIONS_TIME_ZONE_OFFSET_CONVERSIONS_HPP_INCLUDED
constexpr int64_t SEC_PER_HOUR
Seconds per hour.
constexpr int64_t SEC_PER_MIN
Seconds per minute.
TIME_SHIELD_CONSTEXPR bool is_valid_tz_offset(tz_t off) noexcept
Check if a numeric offset is within supported bounds.
T to_time_zone(tz_t offset)
Converts an integer to a time zone structure.
TIME_SHIELD_CONSTEXPR tz_t tz_offset_hm(int hour, int min=0) noexcept
Build offset in seconds from hours/minutes.
TIME_SHIELD_CONSTEXPR tz_t to_tz_offset(const T &tz) noexcept
Convert time zone struct to offset in seconds.
int32_t tz_t
Time zone offset in minutes from UTC (e.g., +180 = UTC+3).
Definition types.hpp:60
Main namespace for the Time Shield library.