Time Shield Library
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_TIME_ZONE_OFFSET_CONVERSIONS_HPP_INCLUDED
4#define _TIME_SHIELD_TIME_ZONE_OFFSET_CONVERSIONS_HPP_INCLUDED
5
8
9#include "config.hpp"
10#include "constants.hpp"
11#include "time_zone_struct.hpp"
12#include "types.hpp"
13
14namespace time_shield {
15
18
24 template<class T = TimeZoneStruct>
25 inline T to_time_zone(tz_t offset) {
26 const int64_t off = static_cast<int64_t>(offset);
27 const int64_t abs_val = (off < 0) ? -off : off;
28
29 T tz;
30 tz.hour = static_cast<decltype(tz.hour)>(abs_val / static_cast<int64_t>(SEC_PER_HOUR));
31 tz.min = static_cast<decltype(tz.min)>(
32 (abs_val % static_cast<int64_t>(SEC_PER_HOUR)) / static_cast<int64_t>(SEC_PER_MIN)
33 );
34 tz.is_positive = (off >= 0);
35 return tz;
36 }
37
40 template<class T>
41 TIME_SHIELD_CONSTEXPR inline tz_t to_tz_offset(const T& tz) noexcept {
42 const int sign = tz.is_positive ? 1 : -1;
43 const int64_t sec = static_cast<int64_t>(tz.hour) * SEC_PER_HOUR
44 + static_cast<int64_t>(tz.min) * SEC_PER_MIN;
45 return static_cast<tz_t>(sign * sec);
46 }
47
51 TIME_SHIELD_CONSTEXPR inline tz_t tz_offset_hm(int hour, int min = 0) noexcept {
52 const int sign = (hour < 0) ? -1 : 1;
53 const int64_t ah = (hour < 0) ? -static_cast<int64_t>(hour) : static_cast<int64_t>(hour);
54 const int64_t am = (min < 0) ? -static_cast<int64_t>(min) : static_cast<int64_t>(min);
55 return static_cast<tz_t>(sign * (ah * SEC_PER_HOUR + am * SEC_PER_MIN));
56 }
57
60 TIME_SHIELD_CONSTEXPR inline bool is_valid_tz_offset(tz_t off) noexcept {
61 // conservative range: [-12:00, +14:00]
62 return off % 60 == 0
63 && off >= -12 * SEC_PER_HOUR
64 && off <= 14 * SEC_PER_HOUR;
65 }
66
68
69}; // namespace time_shield
70
71#endif // _TIME_SHIELD_TIME_ZONE_OFFSET_CONVERSIONS_HPP_INCLUDED
Configuration macros for the library.
Header file with time-related constants.
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.
Header for time zone structure and related functions.
Type definitions for time-related units and formats.