NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
DateTime/DateTime.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#ifndef NUMCPP_NO_USE_BOOST
31
32#include <chrono>
33#include <ctime>
34#include <iostream>
35#include <regex>
36#include <sstream>
37#include <stdexcept>
38#include <string>
39
40#include "boost/date_time/posix_time/posix_time.hpp"
41
43
44namespace nc
45{
46 //================================================================================
47 // Class Description:
50 {
51 public:
52 static constexpr int MAX_MONTH = 12;
53 static constexpr int MAX_DAY = 31;
54 static constexpr int MAX_HOUR = 23;
55 static constexpr int MAX_MINUTE = 59;
56 static constexpr int MAX_SECOND = 59;
57
58 //============================================================================
59 // Method Description:
62 DateTime() = default;
63
64 //============================================================================
65 // Method Description:
70 explicit DateTime(const TimePoint& tp)
71 {
72 auto tpSubSeconds = std::chrono::duration_cast<Duration>(tp.time_since_epoch());
73 auto fractionalSecond = static_cast<double>(tpSubSeconds.count() % Duration::period::den) /
74 static_cast<double>(Duration::period::den);
75 auto time = Clock::to_time_t(std::chrono::time_point_cast<Clock::duration>(tp));
76 std::tm tm{};
77#ifdef _MSC_VER
78 gmtime_s(&tm, &time);
79#else
80 gmtime_r(&time, &tm);
81#endif
82
83 setYear(tm.tm_year + TM_EPOCH_YEAR);
84 setMonth(tm.tm_mon + 1);
85 setDay(tm.tm_mday);
86 setHour(tm.tm_hour);
87 setMinute(tm.tm_min);
88 setSecond(tm.tm_sec);
90 }
91
92 //============================================================================
93 // Method Description:
98 explicit DateTime(const std::string& timestamp) :
99 DateTime(strToTimepoint(timestamp))
100 {
101 }
102
103 //============================================================================
104 // Method Description:
115 DateTime(int year, int month, int day, int hour, int minute, int second, double fractionalSecond = 0.0) noexcept
116 :
117 year_(year),
118 month_(month),
119 day_(day),
120 hour_(hour),
121 minute_(minute),
122 second_(second),
123 fractionalSecond_(fractionalSecond)
124 {
125 }
126
127 //============================================================================
128 // Method Description:
133 [[nodiscard]] int year() const noexcept
134 {
135 return year_;
136 }
137
138 //============================================================================
139 // Method Description:
144 void setYear(int year)
145 {
146 if (year < 0)
147 {
148 throw std::invalid_argument("input year must be greater than zero");
149 }
150 year_ = year;
151 }
152
153 //============================================================================
154 // Method Description:
159 [[nodiscard]] int month() const noexcept
160 {
161 return month_;
162 }
163
164 //============================================================================
165 // Method Description:
170 void setMonth(int month)
171 {
172 if (month < 1)
173 {
174 throw std::invalid_argument("input month must be greater than one");
175 }
176 if (month > MAX_MONTH)
177 {
178 throw std::invalid_argument("input month must be less than DateTime::MAX_MONTH");
179 }
180 month_ = month;
181 }
182
183 //============================================================================
184 // Method Description:
189 [[nodiscard]] int day() const noexcept
190 {
191 return day_;
192 }
193
194 //============================================================================
195 // Method Description:
200 void setDay(int day)
201 {
202 if (day < 1)
203 {
204 throw std::invalid_argument("input day must be greater than one");
205 }
206 if (day > MAX_DAY)
207 {
208 throw std::invalid_argument("input day must be less than DateTime::MAX_DAY");
209 }
210 day_ = day;
211 }
212
213 //============================================================================
214 // Method Description:
219 [[nodiscard]] int hour() const noexcept
220 {
221 return hour_;
222 }
223
224 //============================================================================
225 // Method Description:
230 void setHour(int hour)
231 {
232 if (hour < 0)
233 {
234 throw std::invalid_argument("input hour must be greater than zero");
235 }
236 if (hour > MAX_HOUR)
237 {
238 throw std::invalid_argument("input hour must be less than DateTime::MAX_HOUR");
239 }
240 hour_ = hour;
241 }
242
243 //============================================================================
244 // Method Description:
249 [[nodiscard]] int minute() const noexcept
250 {
251 return minute_;
252 }
253
254 //============================================================================
255 // Method Description:
261 {
262 if (minute < 0)
263 {
264 throw std::invalid_argument("input minute must be greater than zero");
265 }
266 if (minute > MAX_MINUTE)
267 {
268 throw std::invalid_argument("input minute must be less than DateTime::MAX_MINUTE");
269 }
270 minute_ = minute;
271 }
272
273 //============================================================================
274 // Method Description:
279 [[nodiscard]] int second() const noexcept
280 {
281 return second_;
282 }
283
284 //============================================================================
285 // Method Description:
291 {
292 if (second < 0)
293 {
294 throw std::invalid_argument("input second must be greater than zero");
295 }
296 if (second > MAX_SECOND)
297 {
298 throw std::invalid_argument("input second must be less than DateTime::MAX_SECOND");
299 }
300 second_ = second;
301 }
302
303 //============================================================================
304 // Method Description:
309 [[nodiscard]] double fractionalSecond() const noexcept
310 {
311 return fractionalSecond_;
312 }
313
314 //============================================================================
315 // Method Description:
321 {
323 {
324 throw std::invalid_argument("input fractionalSecond must be in the range [0, 1)");
325 }
326 fractionalSecond_ = fractionalSecond;
327 }
328
329 //============================================================================
330 // Method Description:
335 [[nodiscard]] TimePoint toTimePoint() const
336 {
337 std::tm t{};
338 t.tm_year = year_ - TM_EPOCH_YEAR;
339 t.tm_mon = month_ - 1; // tm is 0 based months
340 t.tm_mday = day_;
341 t.tm_hour = hour_;
342 t.tm_min = minute_;
343 t.tm_sec = second_;
344 auto timePoint = Clock::from_time_t(
345#ifdef _MSC_VER
346 _mkgmtime
347#else
348 timegm
349#endif
350 (&t));
351 return std::chrono::time_point_cast<TimePoint::duration>(timePoint) +
352 std::chrono::nanoseconds(static_cast<int64_t>(fractionalSecond_ * SECONDS_TO_NANOSECONDS));
353 }
354
355 //============================================================================
356 // Method Description:
361 [[nodiscard]] std::string toStr() const
362 {
363 const auto timePoint = toTimePoint();
364 const auto timeSinceEpoch = timePoint.time_since_epoch().count();
365 time_t secondsFromEpoch = timeSinceEpoch / Duration::period::den;
366 const auto fractionalSeconds = static_cast<double>(timeSinceEpoch % Duration::period::den) /
367 static_cast<double>(Duration::period::den);
368
369 std::tm tm{};
370#ifdef _MSC_VER
371 gmtime_s(&tm, &secondsFromEpoch);
372#else
373 gmtime_r(&secondsFromEpoch, &tm);
374#endif
375
376 std::stringstream ss;
377 if (fractionalSeconds > 0)
378 {
379 const auto format = "%Y-%m-%dT%H:%M:%S.%msZ";
380 std::stringstream ssFractionalSecond;
381 ssFractionalSecond.precision(NANO_SECOND_PRECESION);
382 ssFractionalSecond << std::fixed << fractionalSeconds;
383 auto fractionalSecondStr = ssFractionalSecond.str();
384 // strip of the preceding "0." and any trailing zeros
385 fractionalSecondStr = fractionalSecondStr.substr(2, fractionalSecondStr.size());
386 fractionalSecondStr = fractionalSecondStr.substr(0, fractionalSecondStr.find_last_not_of('0') + 1);
387 const auto fractionalSecondsFormat = std::regex_replace(format, std::regex("%ms"), fractionalSecondStr);
388 ss << std::put_time(&tm, fractionalSecondsFormat.c_str());
389 }
390 else
391 {
392 const auto format = "%Y-%m-%dT%H:%M:%SZ";
393 ss << std::put_time(&tm, format);
394 }
395
396 return ss.str();
397 }
398
399 //============================================================================
400 // Method Description:
406 [[nodiscard]] static DateTime now() noexcept
407 {
408 return DateTime(Clock::now());
409 }
410
411 //============================================================================
412 // Method Description:
417 static TimePoint strToTimepoint(const std::string& timestamp)
418 {
419 const std::regex regexIsoTime{ R"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d+)?Z)" };
420 if (!std::regex_match(timestamp, regexIsoTime))
421 {
422 throw std::invalid_argument("Invalid iso timestamp format");
423 }
424
425 auto convertedTime = boost::posix_time::ptime{};
426 try
427 {
428 convertedTime = boost::posix_time::from_iso_extended_string(timestamp.substr(0, timestamp.size() - 1));
429 }
430 catch (...)
431 {
432 throw std::invalid_argument("Invalid iso timestamp format");
433 }
434
435 const auto fromEpoch = convertedTime - POSIX_EPOCH;
436 return TimePoint{ Duration{ fromEpoch.total_nanoseconds() } };
437 }
438
439 private:
440 static constexpr int TM_EPOCH_YEAR = 1900;
441 static constexpr int POSIX_EPOCH_YEAR = 1970;
442 static inline const std::string POSIX_EPOCH_STR{ "1970-01-01T00:00:00" };
443 static inline const boost::posix_time::ptime POSIX_EPOCH{ boost::posix_time::from_iso_extended_string(
444 POSIX_EPOCH_STR) };
445 static constexpr double SECONDS_TO_NANOSECONDS = 1e9;
446 static constexpr int NANO_SECOND_PRECESION = 9;
447
449 int year_{ POSIX_EPOCH_YEAR };
451 int month_{ 1 };
453 int day_{ 1 };
455 int hour_{ 0 };
457 int minute_{ 0 };
459 int second_{ 0 };
461 double fractionalSecond_{ 0.0 };
462 };
463
464 //============================================================================
465 // Method Description:
472 [[nodiscard]] inline bool operator==(const DateTime& lhs, const DateTime& rhs) noexcept
473 {
474 return lhs.toTimePoint() == rhs.toTimePoint();
475 }
476
477 //============================================================================
478 // Method Description:
485 [[nodiscard]] inline bool operator!=(const DateTime& lhs, const DateTime& rhs) noexcept
486 {
487 return !(lhs == rhs);
488 }
489
490 //============================================================================
491 // Method Description:
498 [[nodiscard]] inline bool operator<(const DateTime& lhs, const DateTime& rhs) noexcept
499 {
500 return lhs.toTimePoint() < rhs.toTimePoint();
501 }
502
503 //============================================================================
504 // Method Description:
511 [[nodiscard]] inline bool operator<=(const DateTime& lhs, const DateTime& rhs) noexcept
512 {
513 return lhs.toTimePoint() <= rhs.toTimePoint();
514 }
515
516 //============================================================================
517 // Method Description:
524 [[nodiscard]] inline bool operator>(const DateTime& lhs, const DateTime& rhs) noexcept
525 {
526 return lhs.toTimePoint() > rhs.toTimePoint();
527 }
528
529 //============================================================================
530 // Method Description:
537 [[nodiscard]] inline bool operator>=(const DateTime& lhs, const DateTime& rhs) noexcept
538 {
539 return lhs.toTimePoint() >= rhs.toTimePoint();
540 }
541
542 //============================================================================
543 // Method Description:
550 [[nodiscard]] inline Duration operator-(const DateTime& lhs, const DateTime& rhs) noexcept
551 {
552 return lhs.toTimePoint() - rhs.toTimePoint();
553 }
554
555 //============================================================================
556 // Method Description:
563 inline std::ostream& operator<<(std::ostream& os, const DateTime& datetime) noexcept
564 {
565 os << "DateTime:\n";
566 os << "\tyear: " << datetime.year() << '\n';
567 os << "\tmonth: " << datetime.month() << '\n';
568 os << "\tday: " << datetime.day() << '\n';
569 os << "\thour: " << datetime.hour() << '\n';
570 os << "\tminute: " << datetime.minute() << '\n';
571 os << "\tsecond: " << datetime.second() << '\n';
572 os << "\tfractionalSecond: " << datetime.fractionalSecond() << '\n';
573 return os;
574 }
575} // namespace nc
576
577#endif
Date Time class for working with iso formatted date times.
Definition DateTime/DateTime.hpp:50
void setFractionalSecond(double fractionalSecond)
fractionalSecond setter
Definition DateTime/DateTime.hpp:320
void setHour(int hour)
hour setter
Definition DateTime/DateTime.hpp:230
static constexpr int MAX_HOUR
Definition DateTime/DateTime.hpp:54
int hour() const noexcept
hour getter
Definition DateTime/DateTime.hpp:219
int second() const noexcept
second getter
Definition DateTime/DateTime.hpp:279
DateTime()=default
TimePoint toTimePoint() const
Converts the struct to a TimePoint.
Definition DateTime/DateTime.hpp:335
static constexpr int MAX_MINUTE
Definition DateTime/DateTime.hpp:55
DateTime(int year, int month, int day, int hour, int minute, int second, double fractionalSecond=0.0) noexcept
Definition DateTime/DateTime.hpp:115
int year() const noexcept
year getter
Definition DateTime/DateTime.hpp:133
void setSecond(int second)
second setter
Definition DateTime/DateTime.hpp:290
static constexpr int MAX_DAY
Definition DateTime/DateTime.hpp:53
int minute() const noexcept
minute getter
Definition DateTime/DateTime.hpp:249
DateTime(const std::string &timestamp)
Definition DateTime/DateTime.hpp:98
void setDay(int day)
day setter
Definition DateTime/DateTime.hpp:200
double fractionalSecond() const noexcept
fractionalSecond getter
Definition DateTime/DateTime.hpp:309
void setMonth(int month)
month setter
Definition DateTime/DateTime.hpp:170
static TimePoint strToTimepoint(const std::string &timestamp)
Converts the struct to an iso string.
Definition DateTime/DateTime.hpp:417
std::string toStr() const
Converts the struct to an iso string.
Definition DateTime/DateTime.hpp:361
static constexpr int MAX_SECOND
Definition DateTime/DateTime.hpp:56
static constexpr int MAX_MONTH
Definition DateTime/DateTime.hpp:52
void setMinute(int minute)
minute setter
Definition DateTime/DateTime.hpp:260
int month() const noexcept
month getter
Definition DateTime/DateTime.hpp:159
int day() const noexcept
day getter
Definition DateTime/DateTime.hpp:189
static DateTime now() noexcept
Factory static method for returning a DateTime object cooresponding to the system clock now.
Definition DateTime/DateTime.hpp:406
DateTime(const TimePoint &tp)
Definition DateTime/DateTime.hpp:70
void setYear(int year)
year setter
Definition DateTime/DateTime.hpp:144
Definition Cartesian.hpp:39
bool operator==(const DateTime &lhs, const DateTime &rhs) noexcept
Equality operator for DateTime.
Definition DateTime/DateTime.hpp:472
bool operator>=(const std::complex< T > &lhs, const std::complex< T > &rhs) noexcept
Definition StdComplexOperators.hpp:98
Duration operator-(const DateTime &lhs, const DateTime &rhs) noexcept
Subtraction operator.
Definition DateTime/DateTime.hpp:550
bool operator>(const std::complex< T > &lhs, const std::complex< T > &rhs) noexcept
Definition StdComplexOperators.hpp:84
bool operator!=(const DateTime &lhs, const DateTime &rhs) noexcept
Non Equality operator for DateTime.
Definition DateTime/DateTime.hpp:485
bool operator<(const std::complex< T > &lhs, const std::complex< T > &rhs) noexcept
Definition StdComplexOperators.hpp:46
std::ostream & operator<<(std::ostream &os, Duration duration)
Output stream operator for the Duration type.
Definition Clock.hpp:30
bool operator<=(const std::complex< T > &lhs, const std::complex< T > &rhs) noexcept
Definition StdComplexOperators.hpp:65
std::chrono::nanoseconds Duration
Duration Type.
Definition Clock.hpp:16
std::chrono::time_point< Clock, Duration > TimePoint
TimePoint Type.
Definition Clock.hpp:21