Time Shield Library
C++ library for working with time
Loading...
Searching...
No Matches
time_parser.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _TIME_SHIELD_TIME_PARSER_HPP_INCLUDED
3#define _TIME_SHIELD_TIME_PARSER_HPP_INCLUDED
4
10
11#include "enums.hpp"
12#include "constants.hpp"
13#include "date_time_struct.hpp"
14#include "time_zone_struct.hpp"
15#include "validation.hpp"
16#include "time_conversions.hpp"
17#include <regex>
18#include <algorithm>
19#include <locale>
20#include <array>
21#include <stdexcept>
22#include <sstream>
23#include <cctype>
24
25namespace time_shield {
26
58
64 template<class T = Month>
65 T get_month_number(const std::string& month) {
66 if (month.empty()) throw std::invalid_argument("Invalid month name");
67
68 std::string month_copy = month;
69 std::transform(month_copy.begin(), month_copy.end(), month_copy.begin(), [](char &ch) {
70 return std::use_facet<std::ctype<char>>(std::locale()).tolower(ch);
71 });
72 month_copy[0] = static_cast<char>(std::toupper(month_copy[0]));
73
74 static const std::array<std::string, 12> short_names = {
75 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
76 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
77 };
78 static const std::array<std::string, 12> full_names = {
79 "January", "February", "March", "April", "May", "June",
80 "July", "August", "September", "October", "November", "December"
81 };
82
83 for(int i = 0; i < MONTHS_PER_YEAR; ++i) {
84 if (month == short_names[i] || month == full_names[i]) {
85 return static_cast<T>(i + 1);
86 }
87 }
88 throw std::invalid_argument("Invalid month name");
89 }
90
93 template<class T = Month>
94 T month_of_year(const std::string& month) {
95 return get_month_number(month);
96 }
97
98//------------------------------------------------------------------------------
99
105 template<class T = Month>
106 bool try_get_month_number(const std::string& month, T& value) {
107 if (month.empty()) return false;
108
109 std::string month_copy = month;
110 std::transform(month_copy.begin(), month_copy.end(), month_copy.begin(), [](char &ch) {
111 return std::use_facet<std::ctype<char>>(std::locale()).tolower(ch);
112 });
113 month_copy[0] = static_cast<char>(std::toupper(month_copy[0]));
114
115 static const std::array<std::string, MONTHS_PER_YEAR> short_names = {
116 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
117 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
118 };
119 static const std::array<std::string, MONTHS_PER_YEAR> full_names = {
120 "January", "February", "March", "April", "May", "June",
121 "July", "August", "September", "October", "November", "December"
122 };
123
124 for (int i = 0; i < MONTHS_PER_YEAR; ++i) {
125 if (month_copy == short_names[i] || month_copy == full_names[i]) {
126 value = static_cast<T>(i + 1);
127 return true;
128 }
129 }
130 return false;
131 }
132
135 template<class T = Month>
136 bool get_month_number(const std::string& month, T& value) {
137 return try_get_month_number(month, value);
138 }
139
142 template<class T = Month>
143 bool month_of_year(const std::string& month, T& value) {
144 return try_get_month_number(month, value);
145 }
146
147//------------------------------------------------------------------------------
148
155 bool parse_time_zone(const std::string& tz_str, TimeZoneStruct &tz) {
156 if (tz_str.empty()) {
157 tz.hour = 0;
158 tz.min = 0;
159 tz.is_positive = true;
160 return true;
161 }
162 if (tz_str == "Z") {
163 tz.hour = 0;
164 tz.min = 0;
165 tz.is_positive = true;
166 return true;
167 }
168 tz.is_positive = (tz_str[0] == '+');
169 tz.hour = std::stoi(tz_str.substr(1, 2));
170 tz.min = std::stoi(tz_str.substr(4, 2));
171 return is_valid_time_zone(tz);
172 }
173
176 inline bool parse_tz(const std::string& tz_str, TimeZoneStruct &tz) {
177 return parse_time_zone(tz_str, tz);
178 }
179
180//------------------------------------------------------------------------------
181
190 const std::string& input,
191 DateTimeStruct &dt,
192 TimeZoneStruct &tz) {
193 // Регулярное выражение для даты в формате ISO8601
194 static const std::regex date_regex(R"((\d{4})[-\/\.](\d{2})[-\/\.](\d{2}))");
195 std::smatch date_match;
196
197 // Регулярное выражение для времени в формате ISO8601 с часовым поясом и без
198 static const std::regex time_regex(R"((\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?)");
199 std::smatch time_match;
200
202 tz = create_time_zone_struct(0, 0);
203
204 // Парсинг даты
205 if (std::regex_search(input, date_match, date_regex)) {
206 dt.year = std::stoll(date_match[1].str());
207 dt.mon = std::stoi(date_match[2].str());
208 dt.day = std::stoi(date_match[3].str());
209 } else {
210 return false;
211 }
212
213 // Парсинг времени и часового пояса
214 if (std::regex_search(input, time_match, time_regex)) {
215 dt.hour = std::stoi(time_match[1].str());
216 dt.min = std::stoi(time_match[2].str());
217 dt.sec = std::stoi(time_match[3].str());
218 if (time_match[4].matched) {
219 dt.ms = std::stoi(time_match[4].str());
220 }
221 if (time_match[5].matched) {
222 if (!parse_time_zone(time_match[5].str(), tz)) return false;
223 }
224 return is_valid_date_time(dt);
225 }
226 return true;
227 }
228
234 inline bool str_to_ts(const std::string &str, ts_t& ts) {
237 if (!parse_iso8601(str, dt, tz)) return false;
238 try {
239 ts = to_timestamp(dt) + to_offset(tz);
240 return true;
241 } catch(...) {}
242 return false;
243 }
244
250 inline bool str_to_ts_ms(const std::string &str, ts_ms_t& ts) {
253 if (!parse_iso8601(str, dt, tz)) return false;
254 try {
256 return true;
257 } catch(...) {}
258 return false;
259 }
260
266 inline bool str_to_fts(const std::string &str, fts_t& ts) {
269 if (!parse_iso8601(str, dt, tz)) return false;
270 try {
271 ts = to_ftimestamp(dt) + static_cast<fts_t>(to_offset(tz));
272 return true;
273 } catch(...) {}
274 return false;
275 }
276
282 inline ts_t ts(const std::string& str) {
283 ts_t ts = 0;
284 str_to_ts(str, ts);
285 return ts;
286 }
287
293 inline ts_ms_t ts_ms(const std::string& str) {
294 ts_ms_t ts = 0;
295 str_to_ts_ms(str, ts);
296 return ts;
297 }
298
304 inline fts_t fts(const std::string& str) {
305 fts_t ts = 0;
306 str_to_fts(str, ts);
307 return ts;
308 }
309
310 //--------------------------------------------------------------------------
311
323 template<class T = int>
324 inline bool sec_of_day(const std::string& str, T& sec) {
325 if (str.empty()) return false;
326
327 const char* p = str.c_str();
328 int parts[3] = {0, 0, 0}; // hour, minute, second
329 int idx = 0;
330
331 while (*p && idx < 3) {
332 // Parse integer
333 int value = 0;
334 bool has_digit = false;
335
336 while (*p >= '0' && *p <= '9') {
337 has_digit = true;
338 value = value * 10 + (*p - '0');
339 ++p;
340 }
341
342 if (!has_digit) return false;
343 parts[idx++] = value;
344
345 // Expect colon or end
346 if (*p == ':') {
347 ++p;
348 } else if (*p == '\0') {
349 break;
350 } else {
351 return false; // unexpected character
352 }
353 }
354
355 if (idx == 0) return false;
356 if (!is_valid_time(parts[0], parts[1], parts[2])) return false;
357
358 sec = static_cast<T>(sec_of_day(parts[0], parts[1], parts[2]));
359 return true;
360 }
361
372 template<class T = int>
373 inline T sec_of_day(const std::string& str) {
374 T value{};
375 if (sec_of_day(str, value))
376 return value;
377 return static_cast<T>(SEC_PER_DAY);
378 }
379
380
386 inline ts_t ts(const char *str) {
387 ts_t ts = 0;
388 str_to_ts(str, ts);
389 return ts;
390 }
391
397 inline ts_ms_t ts_ms(const char *str) {
398 ts_ms_t ts = 0;
399 str_to_ts_ms(str, ts);
400 return ts;
401 }
402
408 inline fts_t fts(const char *str) {
409 fts_t ts = 0;
410 str_to_fts(str, ts);
411 return ts;
412 }
413
415
416};
417
418#endif // _TIME_SHIELD_TIME_PARSER_HPP_INCLUDED
Header file with time-related constants.
Header for date and time structure and related functions.
Header file with enumerations for weekdays, months, and other time-related categories.
const int64_t MONTHS_PER_YEAR
Months per year.
constexpr int64_t SEC_PER_DAY
Seconds per day.
constexpr T sec_of_day(ts_t ts=ts()) noexcept
Get the second of the day.
TIME_SHIELD_CONSTEXPR T month_of_year(ts_t ts) noexcept
Get the month of the year.
TIME_SHIELD_CONSTEXPR ts_t ts(year_t year, int month, int day)
Alias for to_timestamp.
constexpr fts_t to_ftimestamp(const T &date_time)
Alias for dt_to_ftimestamp.
TIME_SHIELD_CONSTEXPR ts_t to_timestamp(const T &date_time)
Alias for dt_to_timestamp function.
constexpr T1 sec_to_ms(T2 ts) noexcept
Converts a timestamp from seconds to milliseconds.
TIME_SHIELD_CONSTEXPR ts_t to_timestamp_ms(const T &date_time)
Alias for dt_to_timestamp_ms function.
bool str_to_ts_ms(const std::string &str, ts_ms_t &ts)
Convert an ISO8601 string to a millisecond timestamp (ts_ms_t).
bool parse_iso8601(const std::string &input, DateTimeStruct &dt, TimeZoneStruct &tz)
Parse a date and time string in ISO8601 format.
bool try_get_month_number(const std::string &month, T &value)
Get the month number by name, with output parameter.
T get_month_number(const std::string &month)
Get the month number by name.
bool str_to_ts(const std::string &str, ts_t &ts)
Convert an ISO8601 string to a timestamp (ts_t).
bool str_to_fts(const std::string &str, fts_t &ts)
Convert an ISO8601 string to a floating-point timestamp (fts_t).
bool parse_time_zone(const std::string &tz_str, TimeZoneStruct &tz)
Parse a time zone string into a TimeZoneStruct.
bool parse_tz(const std::string &tz_str, TimeZoneStruct &tz)
Alias for parse_time_zone function.
tz_t to_offset(const TimeZoneStruct &tz)
Alias for time_zone_struct_to_offset function.
const DateTimeStruct create_date_time_struct(int64_t year, int mon=1, int day=1, int hour=0, int min=0, int sec=0, int ms=0)
Creates a DateTimeStruct instance.
TimeZoneStruct create_time_zone_struct(int hour, int min, bool is_positive=true)
Creates a TimeZoneStruct instance.
int64_t ts_t
Unix timestamp in seconds since 1970‑01‑01T00:00:00Z.
Definition types.hpp:45
int64_t ts_ms_t
Unix timestamp in milliseconds since epoch.
Definition types.hpp:46
double fts_t
Floating-point timestamp (fractional seconds since epoch).
Definition types.hpp:48
ts_t ts() noexcept
Get the current UTC timestamp in seconds.
ts_ms_t ts_ms() noexcept
Get the current UTC timestamp in milliseconds.
fts_t fts() noexcept
Get the current UTC timestamp in floating-point seconds.
TIME_SHIELD_CONSTEXPR bool is_valid_time_zone(T hour, T min) noexcept
Check if the time zone is valid.
TIME_SHIELD_CONSTEXPR bool is_valid_time(T1 hour, T1 min, T1 sec, T2 ms=0) noexcept
Checks the correctness of the specified time.
TIME_SHIELD_CONSTEXPR bool is_valid_date_time(T1 year, T2 month, T2 day, T2 hour=0, T2 min=0, T2 sec=0, T3 ms=0) noexcept
Checks the correctness of a date and time.
Main namespace for the Time Shield library.
Structure to represent date and time.
int ms
Millisecond component of time (0-999)
int hour
Hour component of time (0-23)
int64_t year
Year component of the date.
int day
Day component of the date (1-31).
int min
Minute component of time (0-59)
int mon
Month component of the date (1-12).
int sec
Second component of time (0-59)
Structure to represent time zone information.
int hour
Hour component of time (0-23)
int min
Minute component of time (0-59)
bool is_positive
True if the time zone offset is positive, false if negative.
Header file for time conversion functions.
Header for time zone structure and related functions.
Header file with time-related validation functions.