Debian Codegraph @

chrono/datetime.h

raw symbols SCIP
1 #ifndef CHRONO_UTILITIES_DATETIME_H
2 #define CHRONO_UTILITIES_DATETIME_H
3
4 #include "./timespan.h"
5
6 #include "../misc/flagenumclass.h"
7
8 #include <cstdint>
9 #include <ctime>
10 #include <limits>
11 #include <string>
12
13 namespace CppUtilities {
14
15 /*!
16 * \brief Specifies the output format.
17 * \sa DateTime::toString()
18 */
19 enum class DateTimeOutputFormat {
20 DateAndTime, /**< date and time */
21 DateOnly, /**< date only */
22 TimeOnly, /**< time only */
23 DateTimeAndWeekday, /**< date with weekday and time */
24 DateTimeAndShortWeekday, /**< date with abbreviated weekday and time */
25 Iso, /**< ISO format like DateTime::toIsoString() */
26 IsoOmittingDefaultComponents, /**< ISO format like DateTime::toIsoString() omitting default components, e.g. just "2017" instead of "2017-01-01T00:00:00" */
27 };
28
29 /*!
30 * \brief Specifies the day of the week.
31 * \sa DateTime::dayOfWeek()
32 */
33 enum class DayOfWeek {
34 Monday, /**< Monday */
35 Tuesday, /**< Tuesday */
36 Wednesday, /**< Wednesday */
37 Thursday, /**< Thursday */
38 Friday, /**< Friday */
39 Saturday, /**< Saturday */
40 Sunday /**< Sunday */
41 };
42
43 /*!
44 * \brief Specifies the date part.
45 * \remarks Intended for internal use only.
46 * \sa DateTime::getDatePart()
47 */
48 enum class DatePart {
49 Year, /**< year */
50 Month, /**< month */
51 DayOfYear, /**< day of year */
52 Day /**< day */
53 };
54
55 class CPP_UTILITIES_EXPORT DateTime {
56 public:
57 using TickType = std::uint64_t;
58
59 explicit constexpr DateTime();
60 explicit constexpr DateTime(TickType ticks);
61 static DateTime fromDate(int year = 1, int month = 1, int day = 1);
62 static DateTime fromTime(int hour = 0, int minute = 0, int second = 0, double millisecond = 0.0);
63 static DateTime fromDateAndTime(int year = 1, int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, double millisecond = 0.0);
64 static DateTime fromString(const std::string &str);
65 static DateTime fromString(const char *str);
66 static std::pair<DateTime, TimeSpan> fromIsoString(const char *str);
67 static DateTime fromIsoStringGmt(const char *str);
68 static DateTime fromIsoStringLocal(const char *str);
69 static DateTime fromTimeStamp(std::time_t timeStamp);
70 constexpr static DateTime fromTimeStampGmt(std::time_t timeStamp);
71 template <typename TimePoint> static DateTime fromChronoTimePoint(TimePoint timePoint);
72 template <typename TimePoint> constexpr static DateTime fromChronoTimePointGmt(TimePoint timePoint);
73
74 constexpr TickType &ticks();
75 constexpr TickType totalTicks() const;
76 int year() const;
77 int month() const;
78 int day() const;
79 int dayOfYear() const;
80 constexpr DayOfWeek dayOfWeek() const;
81 constexpr int hour() const;
82 constexpr int minute() const;
83 constexpr int second() const;
84 constexpr int millisecond() const;
85 constexpr int microsecond() const;
86 constexpr int nanosecond() const;
87 constexpr bool isNull() const;
88 constexpr TimeSpan timeOfDay() const;
89 bool isLeapYear() const;
90 constexpr bool isEternity() const;
91 constexpr bool isSameDay(const DateTime &other) const;
92 std::string toString(DateTimeOutputFormat format = DateTimeOutputFormat::DateAndTime, bool noMilliseconds = false) const;
93 void toString(std::string &result, DateTimeOutputFormat format = DateTimeOutputFormat::DateAndTime, bool noMilliseconds = false) const;
94 std::string toIsoStringWithCustomDelimiters(
95 TimeSpan timeZoneDelta = TimeSpan(), char dateDelimiter = '-', char timeDelimiter = ':', char timeZoneDelimiter = ':') const;
96 std::string toIsoString(TimeSpan timeZoneDelta = TimeSpan()) const;
97 constexpr std::time_t toTimeStamp() const;
98 static const char *printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation = false);
99
100 static constexpr DateTime eternity();
101 static constexpr DateTime unixEpochStart();
102 static DateTime now();
103 static DateTime gmtNow();
104 static DateTime exactGmtNow();
105 constexpr static bool isLeapYear(int year);
106 static int daysInMonth(int year, int month);
107
108 constexpr bool operator==(const DateTime &other) const;
109 constexpr bool operator!=(const DateTime &other) const;
110 constexpr bool operator<(const DateTime &other) const;
111 constexpr bool operator>(const DateTime &other) const;
112 constexpr bool operator<=(const DateTime &other) const;
113 constexpr bool operator>=(const DateTime &other) const;
114 constexpr DateTime operator+(const TimeSpan &timeSpan) const;
115 constexpr DateTime operator-(const TimeSpan &timeSpan) const;
116 constexpr TimeSpan operator+(const DateTime &other) const;
117 constexpr TimeSpan operator-(const DateTime &other) const;
118 DateTime &operator+=(const TimeSpan &timeSpan);
119 DateTime &operator-=(const TimeSpan &timeSpan);
120
121 private:
122 static TickType dateToTicks(int year, int month, int day);
123 static TickType timeToTicks(int hour, int minute, int second, double millisecond);
124 int getDatePart(DatePart part) const;
125
126 TickType m_ticks;
127 static const int m_daysPerYear;
128 static const int m_daysPer4Years;
129 static const int m_daysPer100Years;
130 static const int m_daysPer400Years;
131 static const int m_daysTo1601;
132 static const int m_daysTo1899;
133 static const int m_daysTo10000;
134 static const int m_daysToMonth365[13];
135 static const int m_daysToMonth366[13];
136 static const int m_daysInMonth365[12];
137 static const int m_daysInMonth366[12];
138 };
139
140 /*!
141 * \brief The DateTimeParts enum specifies which parts of a timestamp are present.
142 */
143 enum class DateTimeParts : std::uint64_t {
144 None = 0, /**< no parts are present */
145 Year = (1 << 0), /**< the year is present */
146 Month = (1 << 1), /**< the month is present */
147 Day = (1 << 2), /**< the day is present */
148 Hour = (1 << 3), /**< the hour is present */
149 Minute = (1 << 4), /**< the minute is present */
150 Second = (1 << 5), /**< the second is present */
151 SubSecond = (1 << 6), /**< the second contains a fractional part */
152 DeltaHour = (1 << 7), /**< the timezone-delta hour is present */
153 DeltaMinute = (1 << 8), /**< the timezone-delta minute is present */
154 Date = Year | Month | Day, /**< year, month and day are present */
155 Time = Hour | Minute | Second | SubSecond, /**< hour, minute and (sub)second are present */
156 DateTime = Date | Time, /**< all parts a DateTime object can represent are present */
157 TimeZoneDelta = DeltaHour | DeltaMinute, /**< the timezone-delta hour and minute are present */
158 All = DateTime | TimeZoneDelta, /**< all parts a DateTime object can represent plus the full timezone-delta are present */
159 };
160
161 struct CPP_UTILITIES_EXPORT DateTimeExpression {
162 DateTime value; /**< The value of the time expression as DateTime object. */
163 TimeSpan delta; /**< The delta of \a value from UTC as TimeSpan object. */
164 DateTimeParts parts = DateTimeParts::None; /**< The parts present in the expression as flag enum. */
165
166 constexpr DateTime gmt() const;
167 constexpr bool operator==(const DateTimeExpression &other) const;
168 std::string toIsoString(char dateDelimiter = '-', char timeDelimiter = ':', char timeZoneDelimiter = ':') const;
169 static DateTimeExpression fromIsoString(const char *str);
170 static DateTimeExpression fromString(const char *str);
171 };
172
173 /*!
174 * \brief Returns the value in UTC time.
175 */
176 constexpr DateTime DateTimeExpression::gmt() const
177 {
178 return value - delta;
179 }
180
181 /*!
182 * \brief Returns whether the expressions are equivalent.
183 */
184 constexpr bool DateTimeExpression::operator==(const DateTimeExpression &other) const
185 {
186 return value == other.value && delta == other.delta && parts == other.parts;
187 }
188
189 /*!
190 * \brief Constructs a DateTime.
191 */
192 constexpr inline DateTime::DateTime()
193 : m_ticks(0)
194 {
195 }
196
197 /*!
198 * \brief Constructs a DateTime with the specified number of \a ticks.
199 */
200 constexpr inline DateTime::DateTime(TickType ticks)
201 : m_ticks(ticks)
202 {
203 }
204
205 /*!
206 * \brief Constructs a DateTime to the specified \a year, \a month, and \a day.
207 * \throws Throws a ConversionException if the specified \a year, \a month or \a day is out-of-range.
208 */
209 inline DateTime DateTime::fromDate(int year, int month, int day)
210 {
211 return DateTime(dateToTicks(year, month, day));
212 }
213
214 /*!
215 * \brief Constructs a DateTime to the specified \a hour, \a minute, \a second and \a millisecond.
216 * \throws Throws a ConversionException if the specified \a hour, \a minute, \a second or \a millisecond is out-of-range.
217 */
218 inline DateTime DateTime::fromTime(int hour, int minute, int second, double millisecond)
219 {
220 return DateTime(timeToTicks(hour, minute, second, millisecond));
221 }
222
223 /*!
224 * \brief Constructs a DateTime to the specified \a year, \a month, \a day, \a hour, \a minute, \a second and \a millisecond.
225 * \throws Throws a ConversionException if the specified \a year, \a month, \a day, \a hour, \a minute, \a second or \a millisecond
226 * is out-of-range.
227 */
228 inline DateTime DateTime::fromDateAndTime(int year, int month, int day, int hour, int minute, int second, double millisecond)
229 {
230 return DateTime(dateToTicks(year, month, day) + timeToTicks(hour, minute, second, millisecond));
231 }
232
233 /*!
234 * \brief Parses the given std::string as DateTime.
235 * \throws Throws a ConversionException if the specified \a str does not match the expected time format.
236 *
237 * The expected format is something like "2012-02-29 15:34:20.033" or "2012/02/29 15:34:20.033". The
238 * delimiters '-', ':' and '/' are exchangeable.
239 *
240 * \sa DateTime::fromIsoString()
241 */
242 inline DateTime DateTime::fromString(const std::string &str)
243 {
244 return fromString(str.data());
245 }
246
247 /*!
248 * \brief Parses the specified ISO date time denotation provided as C-style string.
249 * \returns Returns the parsed UTC time. That means a possibly denoted time zone delta is subtracted from the time stamp.
250 * \throws Throws a ConversionException if the specified \a str does not match the expected time format.
251 * \sa fromIsoString()
252 */
253 inline DateTime DateTime::fromIsoStringGmt(const char *str)
254 {
255 return DateTimeExpression::fromIsoString(str).gmt();
256 }
257
258 /*!
259 * \brief Parses the specified ISO date time denotation provided as C-style string.
260 * \returns Returns the parsed local time. That means a possibly denoted time zone delta is discarded.
261 * \throws Throws a ConversionException if the specified \a str does not match the expected time format.
262 * \sa fromIsoString()
263 */
264 inline DateTime DateTime::fromIsoStringLocal(const char *str)
265 {
266 return DateTimeExpression::fromIsoString(str).value;
267 }
268
269 /*!
270 * \brief Constructs a new DateTime object with the GMT time from the specified UNIX \a timeStamp.
271 */
272 constexpr inline DateTime DateTime::fromTimeStampGmt(std::time_t timeStamp)
273 {
274 return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(timeStamp) * TimeSpan::ticksPerSecond);
275 }
276
277 /*!
278 * \brief Constructs a new DateTime object with the local time from the specified std::chrono::time_point.
279 * \remarks Works only with time points of std::chrono::system_clock so far. C++20 will fix this. Until then this function
280 * should be considered experimental.
281 */
282 template <typename TimePoint> inline DateTime DateTime::fromChronoTimePoint(TimePoint timePoint)
283 {
284 return DateTime::fromTimeStamp(decltype(timePoint)::clock::to_time_t(timePoint));
285 }
286
287 /*!
288 * \brief Constructs a new DateTime object with the GMT time from the specified std::chrono::time_point.
289 * \remarks Works only with time points of std::chrono::system_clock so far. C++20 will fix this. Until then this function
290 * should be considered experimental.
291 */
292 template <typename TimePoint> constexpr DateTime DateTime::fromChronoTimePointGmt(TimePoint timePoint)
293 {
294 return DateTime::fromTimeStampGmt(decltype(timePoint)::clock::to_time_t(timePoint));
295 }
296
297 /*!
298 * \brief Returns a mutable reference to the total ticks.
299 */
300 constexpr inline DateTime::TickType &DateTime::ticks()
301 {
302 return m_ticks;
303 }
304
305 /*!
306 * \brief Returns the number of ticks which represent the value of the current instance.
307 */
308 constexpr inline DateTime::TickType DateTime::totalTicks() const
309 {
310 return m_ticks;
311 }
312
313 /*!
314 * \brief Returns the year component of the date represented by this instance.
315 */
316 inline int DateTime::year() const
317 {
318 return getDatePart(DatePart::Year);
319 }
320
321 /*!
322 * \brief Returns the month component of the date represented by this instance.
323 */
324 inline int DateTime::month() const
325 {
326 return getDatePart(DatePart::Month);
327 }
328
329 /*!
330 * \brief Returns the day component of the date represented by this instance.
331 */
332 inline int DateTime::day() const
333 {
334 return getDatePart(DatePart::Day);
335 }
336
337 /*!
338 * \brief Returns the day of the year represented by this instance.
339 */
340 inline int DateTime::dayOfYear() const
341 {
342 return getDatePart(DatePart::DayOfYear);
343 }
344
345 /*!
346 * \brief Returns the day of the week represented by this instance.
347 * \sa DayOfWeek
348 */
349 constexpr inline DayOfWeek DateTime::dayOfWeek() const
350 {
351 return static_cast<DayOfWeek>((m_ticks / TimeSpan::ticksPerDay) % 7l);
352 }
353
354 /*!
355 * \brief Returns the hour component of the date represented by this instance.
356 */
357 constexpr inline int DateTime::hour() const
358 {
359 return static_cast<int>(m_ticks / TimeSpan::ticksPerHour % 24ul);
360 }
361
362 /*!
363 *\brief Returns the minute component of the date represented by this instance.
364 */
365 constexpr inline int DateTime::minute() const
366 {
367 return static_cast<int>(m_ticks / TimeSpan::ticksPerMinute % 60ul);
368 }
369
370 /*!
371 * \brief Returns the second component of the date represented by this instance.
372 */
373 constexpr inline int DateTime::second() const
374 {
375 return static_cast<int>(m_ticks / TimeSpan::ticksPerSecond % 60ul);
376 }
377
378 /*!
379 * \brief Returns the millisecond component of the date represented by this instance.
380 */
381 constexpr inline int DateTime::millisecond() const
382 {
383 return static_cast<int>(m_ticks / TimeSpan::ticksPerMillisecond % 1000ul);
384 }
385
386 /*!
387 * \brief Returns the microsecond component of the date represented by this instance.
388 */
389 constexpr inline int DateTime::microsecond() const
390 {
391 return static_cast<int>(m_ticks / TimeSpan::ticksPerMicrosecond % 1000ul);
392 }
393
394 /*!
395 * \brief Returns the nanosecond component of the date represented by this instance.
396 * \remarks The accuracy of the DateTime class is 100-nanoseconds. Hence the returned value
397 * will always have two zeros at the end (in decimal representation).
398 */
399 constexpr inline int DateTime::nanosecond() const
400 {
401 return static_cast<int>(m_ticks % 10ul * TimeSpan::nanosecondsPerTick);
402 }
403
404 /*!
405 * \brief Returns true if the date represented by the current DateTime class is null.
406 * \sa DateTime
407 */
408 constexpr inline bool DateTime::isNull() const
409 {
410 return m_ticks == 0;
411 }
412
413 /*!
414 * \brief Returns the time of day as TimeSpan for this instance.
415 */
416 constexpr inline TimeSpan DateTime::timeOfDay() const
417 {
418 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks % TimeSpan::ticksPerDay));
419 }
420
421 /*!
422 * \brief Returns an indication whether the year represented by this instance is a leap year.
423 */
424 inline bool DateTime::isLeapYear() const
425 {
426 return isLeapYear(year());
427 }
428
429 /*!
430 * \brief Returns whether the instance has the maximal number of ticks.
431 */
432 constexpr inline bool DateTime::isEternity() const
433 {
434 return m_ticks == std::numeric_limits<TickType>::max();
435 }
436
437 /*!
438 * \brief Returns an indication whether the specified \a year is a leap year.
439 */
440 constexpr inline bool DateTime::isLeapYear(int year)
441 {
442 return (year % 4 != 0) ? false : ((year % 100 == 0) ? (year % 400 == 0) : true);
443 }
444
445 /*!
446 * \brief Returns the number of days in the specified \a month and \a year.
447 */
448 inline int DateTime::daysInMonth(int year, int month)
449 {
450 return (month >= 1 && month <= 12) ? (isLeapYear(year) ? m_daysInMonth366[month - 1] : m_daysInMonth365[month - 1]) : (0);
451 }
452
453 /*!
454 * \brief Returns and indication whether two DateTime instances represent the same day.
455 */
456 constexpr inline bool DateTime::isSameDay(const DateTime &other) const
457 {
458 return (m_ticks / TimeSpan::ticksPerDay) == (other.m_ticks / TimeSpan::ticksPerDay);
459 }
460
461 /*!
462 * \brief Returns the string representation of the current instance using the specified \a format.
463 * \remarks If \a noMilliseconds is true the date will be rounded to full seconds.
464 * \sa toIsoString() for ISO format
465 */
466 inline std::string DateTime::toString(DateTimeOutputFormat format, bool noMilliseconds) const
467 {
468 std::string result;
469 toString(result, format, noMilliseconds);
470 return result;
471 }
472
473 /*!
474 * \brief Returns the UNIX timestamp for the current instance.
475 */
476 constexpr std::time_t DateTime::toTimeStamp() const
477 {
478 return static_cast<std::time_t>((totalTicks() - DateTime::unixEpochStart().totalTicks()) / TimeSpan::ticksPerSecond);
479 }
480
481 /*!
482 * \brief Constructs a new instance of the DateTime class with the maximal number of ticks.
483 */
484 constexpr inline DateTime DateTime::eternity()
485 {
486 return DateTime(std::numeric_limits<TickType>::max());
487 }
488
489 /*!
490 * \brief Returns the DateTime object for the "1970-01-01T00:00:00Z".
491 */
492 constexpr inline DateTime DateTime::unixEpochStart()
493 {
494 return DateTime(621355968000000000);
495 }
496
497 /*!
498 * \brief Returns a DateTime object that is set to the current date and time on this computer, expressed as the local time.
499 * \remarks The time might be rounded to full seconds. Use exactGmtNow() for better precision.
500 */
501 inline DateTime DateTime::now()
502 {
503 return DateTime::fromTimeStamp(std::time(nullptr));
504 }
505
506 /*!
507 * \brief Returns a DateTime object that is set to the current date and time on this computer, expressed as the GMT time.
508 * \remarks The time might be rounded to full seconds. Use exactGmtNow() for better precision.
509 */
510 inline DateTime DateTime::gmtNow()
511 {
512 return DateTime::fromTimeStampGmt(std::time(nullptr));
513 }
514
515 /*!
516 * \brief Indicates whether two DateTime instances are equal.
517 */
518 constexpr inline bool DateTime::operator==(const DateTime &other) const
519 {
520 return m_ticks == other.m_ticks;
521 }
522
523 /*!
524 * \brief Indicates whether two DateTime instances are not equal.
525 */
526 constexpr inline bool DateTime::operator!=(const DateTime &other) const
527 {
528 return m_ticks != other.m_ticks;
529 }
530
531 /*!
532 * \brief Indicates whether a specified DateTime is less than another specified DateTime.
533 */
534 constexpr inline bool DateTime::operator<(const DateTime &other) const
535 {
536 return m_ticks < other.m_ticks;
537 }
538
539 /*!
540 * \brief Indicates whether a specified DateTime is greater than another specified DateTime.
541 */
542 constexpr inline bool DateTime::operator>(const DateTime &other) const
543 {
544 return m_ticks > other.m_ticks;
545 }
546
547 /*!
548 * \brief Indicates whether a specified DateTime is less or equal than another specified DateTime.
549 */
550 constexpr inline bool DateTime::operator<=(const DateTime &other) const
551 {
552 return m_ticks <= other.m_ticks;
553 }
554
555 /*!
556 * \brief Indicates whether a specified DateTime is greater or equal than another specified DateTime.
557 */
558 constexpr inline bool DateTime::operator>=(const DateTime &other) const
559 {
560 return m_ticks >= other.m_ticks;
561 }
562
563 /*!
564 * \brief Adds another instance.
565 * \returns The result is another DateTime.
566 */
567 constexpr inline DateTime DateTime::operator+(const TimeSpan &timeSpan) const
568 {
569 return DateTime(m_ticks + static_cast<TickType>(timeSpan.m_ticks));
570 }
571
572 /*!
573 * \brief Subtracts another instance.
574 * \returns The result is another DateTime.
575 */
576 constexpr inline DateTime DateTime::operator-(const TimeSpan &timeSpan) const
577 {
578 return DateTime(m_ticks - static_cast<TickType>(timeSpan.m_ticks));
579 }
580
581 /*!
582 * \brief Adds two instances.
583 * \returns The result is a TimeSpan.
584 */
585 constexpr inline TimeSpan DateTime::operator+(const DateTime &other) const
586 {
587 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks + other.m_ticks));
588 }
589
590 /*!
591 * \brief Subtracts two DateTime instances.
592 * \returns The result is a TimeSpan.
593 * \remarks For expressing the delta between two concrete DateTime instances in terms of
594 * years, month and days, use Period::Period instead.
595 */
596 constexpr inline TimeSpan DateTime::operator-(const DateTime &other) const
597 {
598 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks - other.m_ticks));
599 }
600
601 /*!
602 * \brief Adds a TimeSpan to the current instance.
603 */
604 inline DateTime &DateTime::operator+=(const TimeSpan &timeSpan)
605 {
606 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
607 return *this;
608 }
609
610 /*!
611 * \brief Subtracts a TimeSpan from the current instance.
612 */
613 inline DateTime &DateTime::operator-=(const TimeSpan &timeSpan)
614 {
615 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
616 return *this;
617 }
618 } // namespace CppUtilities
619
620 namespace std {
621 /// \brief Computes the hash for the CppUtilities::DateTime instance.
622 template <> struct hash<CppUtilities::DateTime> {
623 inline size_t operator()(const CppUtilities::DateTime &dateTime) const
624 {
625 return hash<CppUtilities::DateTime::TickType>()(dateTime.totalTicks());
626 }
627 };
628 } // namespace std
629
630 CPP_UTILITIES_MARK_FLAG_ENUM_CLASS(CppUtilities, CppUtilities::DateTimeParts);
631
632 #endif // CHRONO_UTILITIES_DATETIME_H