C++ Utilities 5.26.1
Useful C++ classes and routines such as argument parser, IO and conversion utilities
Loading...
Searching...
No Matches
datetime.h
Go to the documentation of this file.
1#ifndef CHRONO_UTILITIES_DATETIME_H
2#define CHRONO_UTILITIES_DATETIME_H
3
4#include "./timespan.h"
5
7
8#include <cstdint>
9#include <ctime>
10#include <limits>
11#include <string>
12
13namespace CppUtilities {
14
28
33enum class DayOfWeek {
34 Monday,
35 Tuesday,
36 Wednesday,
37 Thursday,
38 Friday,
39 Saturday,
40 Sunday
41};
42
48enum class DatePart {
49 Year,
50 Month,
51 DayOfYear,
52 Day
53};
54
56public:
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#if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
105 static DateTime exactGmtNow();
106#endif
107 constexpr static bool isLeapYear(int year);
108 static int daysInMonth(int year, int month);
109
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 bool operator<=(const DateTime &other) const;
115 constexpr bool operator>=(const DateTime &other) const;
116 constexpr DateTime operator+(const TimeSpan &timeSpan) const;
117 constexpr DateTime operator-(const TimeSpan &timeSpan) const;
118 constexpr TimeSpan operator+(const DateTime &other) const;
119 constexpr TimeSpan operator-(const DateTime &other) const;
120 DateTime &operator+=(const TimeSpan &timeSpan);
121 DateTime &operator-=(const TimeSpan &timeSpan);
122
123private:
124 static TickType dateToTicks(int year, int month, int day);
125 static TickType timeToTicks(int hour, int minute, int second, double millisecond);
126 int getDatePart(DatePart part) const;
127
128 TickType m_ticks;
129 static const int m_daysPerYear;
130 static const int m_daysPer4Years;
131 static const int m_daysPer100Years;
132 static const int m_daysPer400Years;
133 static const int m_daysTo1601;
134 static const int m_daysTo1899;
135 static const int m_daysTo10000;
136 static const int m_daysToMonth365[13];
137 static const int m_daysToMonth366[13];
138 static const int m_daysInMonth365[12];
139 static const int m_daysInMonth366[12];
140};
141
145enum class DateTimeParts : std::uint64_t {
146 None = 0,
147 Year = (1 << 0),
148 Month = (1 << 1),
149 Day = (1 << 2),
150 Hour = (1 << 3),
151 Minute = (1 << 4),
152 Second = (1 << 5),
153 SubSecond = (1 << 6),
154 DeltaHour = (1 << 7),
155 DeltaMinute = (1 << 8),
156 Date = Year | Month | Day,
158 DateTime = Date | Time,
161};
162
166 DateTimeParts parts = DateTimeParts::None;
168 constexpr DateTime gmt() const;
169 constexpr bool operator==(const DateTimeExpression &other) const;
170 std::string toIsoString(char dateDelimiter = '-', char timeDelimiter = ':', char timeZoneDelimiter = ':') const;
171 static DateTimeExpression fromIsoString(const char *str);
172 static DateTimeExpression fromString(const char *str);
173};
174
179{
180 return value - delta;
181}
182
186constexpr bool DateTimeExpression::operator==(const DateTimeExpression &other) const
187{
188 return value == other.value && delta == other.delta && parts == other.parts;
189}
190
194constexpr inline DateTime::DateTime()
195 : m_ticks(0)
196{
197}
198
202constexpr inline DateTime::DateTime(TickType ticks)
203 : m_ticks(ticks)
204{
205}
206
211inline DateTime DateTime::fromDate(int year, int month, int day)
212{
213 return DateTime(dateToTicks(year, month, day));
214}
215
220inline DateTime DateTime::fromTime(int hour, int minute, int second, double millisecond)
221{
222 return DateTime(timeToTicks(hour, minute, second, millisecond));
223}
224
230inline DateTime DateTime::fromDateAndTime(int year, int month, int day, int hour, int minute, int second, double millisecond)
231{
232 return DateTime(dateToTicks(year, month, day) + timeToTicks(hour, minute, second, millisecond));
233}
234
244inline DateTime DateTime::fromString(const std::string &str)
245{
246 return fromString(str.data());
247}
248
256{
258}
259
267{
269}
270
274constexpr inline DateTime DateTime::fromTimeStampGmt(std::time_t timeStamp)
275{
276 return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(timeStamp) * TimeSpan::ticksPerSecond);
277}
278
284template <typename TimePoint> inline DateTime DateTime::fromChronoTimePoint(TimePoint timePoint)
285{
286 return DateTime::fromTimeStamp(decltype(timePoint)::clock::to_time_t(timePoint));
287}
288
294template <typename TimePoint> constexpr DateTime DateTime::fromChronoTimePointGmt(TimePoint timePoint)
295{
296 return DateTime::fromTimeStampGmt(decltype(timePoint)::clock::to_time_t(timePoint));
297}
298
303{
304 return m_ticks;
305}
306
311{
312 return m_ticks;
313}
314
318inline int DateTime::year() const
319{
320 return getDatePart(DatePart::Year);
321}
322
326inline int DateTime::month() const
327{
328 return getDatePart(DatePart::Month);
329}
330
334inline int DateTime::day() const
335{
336 return getDatePart(DatePart::Day);
337}
338
342inline int DateTime::dayOfYear() const
343{
344 return getDatePart(DatePart::DayOfYear);
345}
346
351constexpr inline DayOfWeek DateTime::dayOfWeek() const
352{
353 return static_cast<DayOfWeek>((m_ticks / TimeSpan::ticksPerDay) % 7l);
354}
355
359constexpr inline int DateTime::hour() const
360{
361 return static_cast<int>(m_ticks / TimeSpan::ticksPerHour % 24ul);
362}
363
367constexpr inline int DateTime::minute() const
368{
369 return static_cast<int>(m_ticks / TimeSpan::ticksPerMinute % 60ul);
370}
371
375constexpr inline int DateTime::second() const
376{
377 return static_cast<int>(m_ticks / TimeSpan::ticksPerSecond % 60ul);
378}
379
383constexpr inline int DateTime::millisecond() const
384{
385 return static_cast<int>(m_ticks / TimeSpan::ticksPerMillisecond % 1000ul);
386}
387
391constexpr inline int DateTime::microsecond() const
392{
393 return static_cast<int>(m_ticks / TimeSpan::ticksPerMicrosecond % 1000ul);
394}
395
401constexpr inline int DateTime::nanosecond() const
402{
403 return static_cast<int>(m_ticks % 10ul * TimeSpan::nanosecondsPerTick);
404}
405
410constexpr inline bool DateTime::isNull() const
411{
412 return m_ticks == 0;
413}
414
418constexpr inline TimeSpan DateTime::timeOfDay() const
419{
420 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks % TimeSpan::ticksPerDay));
421}
422
426inline bool DateTime::isLeapYear() const
427{
428 return isLeapYear(year());
429}
430
434constexpr inline bool DateTime::isEternity() const
435{
436 return m_ticks == std::numeric_limits<TickType>::max();
437}
438
442constexpr inline bool DateTime::isLeapYear(int year)
443{
444 return (year % 4 != 0) ? false : ((year % 100 == 0) ? (year % 400 == 0) : true);
445}
446
450inline int DateTime::daysInMonth(int year, int month)
451{
452 return (month >= 1 && month <= 12) ? (isLeapYear(year) ? m_daysInMonth366[month - 1] : m_daysInMonth365[month - 1]) : (0);
453}
454
458constexpr inline bool DateTime::isSameDay(const DateTime &other) const
459{
460 return (m_ticks / TimeSpan::ticksPerDay) == (other.m_ticks / TimeSpan::ticksPerDay);
461}
462
468inline std::string DateTime::toString(DateTimeOutputFormat format, bool noMilliseconds) const
469{
470 std::string result;
471 toString(result, format, noMilliseconds);
472 return result;
473}
474
478constexpr std::time_t DateTime::toTimeStamp() const
479{
480 return static_cast<std::time_t>((totalTicks() - DateTime::unixEpochStart().totalTicks()) / TimeSpan::ticksPerSecond);
481}
482
486constexpr inline DateTime DateTime::eternity()
487{
488 return DateTime(std::numeric_limits<TickType>::max());
489}
490
495{
496 return DateTime(621355968000000000);
497}
498
504{
505 return DateTime::fromTimeStamp(std::time(nullptr));
506}
507
513{
514 return DateTime::fromTimeStampGmt(std::time(nullptr));
515}
516
520constexpr inline bool DateTime::operator==(const DateTime &other) const
521{
522 return m_ticks == other.m_ticks;
523}
524
528constexpr inline bool DateTime::operator!=(const DateTime &other) const
529{
530 return m_ticks != other.m_ticks;
531}
532
536constexpr inline bool DateTime::operator<(const DateTime &other) const
537{
538 return m_ticks < other.m_ticks;
539}
540
544constexpr inline bool DateTime::operator>(const DateTime &other) const
545{
546 return m_ticks > other.m_ticks;
547}
548
552constexpr inline bool DateTime::operator<=(const DateTime &other) const
553{
554 return m_ticks <= other.m_ticks;
555}
556
560constexpr inline bool DateTime::operator>=(const DateTime &other) const
561{
562 return m_ticks >= other.m_ticks;
563}
564
569constexpr inline DateTime DateTime::operator+(const TimeSpan &timeSpan) const
570{
571 return DateTime(m_ticks + static_cast<TickType>(timeSpan.m_ticks));
572}
573
578constexpr inline DateTime DateTime::operator-(const TimeSpan &timeSpan) const
579{
580 return DateTime(m_ticks - static_cast<TickType>(timeSpan.m_ticks));
581}
582
587constexpr inline TimeSpan DateTime::operator+(const DateTime &other) const
588{
589 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks + other.m_ticks));
590}
591
598constexpr inline TimeSpan DateTime::operator-(const DateTime &other) const
599{
600 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks - other.m_ticks));
601}
602
606inline DateTime &DateTime::operator+=(const TimeSpan &timeSpan)
607{
608 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
609 return *this;
610}
611
615inline DateTime &DateTime::operator-=(const TimeSpan &timeSpan)
616{
617 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
618 return *this;
619}
620} // namespace CppUtilities
621
622namespace std {
624template <> struct hash<CppUtilities::DateTime> {
625 inline size_t operator()(const CppUtilities::DateTime &dateTime) const
626 {
627 return hash<CppUtilities::DateTime::TickType>()(dateTime.totalTicks());
628 }
629};
630} // namespace std
631
633
634#endif // CHRONO_UTILITIES_DATETIME_H
Represents an instant in time, typically expressed as a date and time of day.
Definition datetime.h:55
std::string toString(DateTimeOutputFormat format=DateTimeOutputFormat::DateAndTime, bool noMilliseconds=false) const
Returns the string representation of the current instance using the specified format.
Definition datetime.h:468
int day() const
Returns the day component of the date represented by this instance.
Definition datetime.h:334
constexpr DayOfWeek dayOfWeek() const
Returns the day of the week represented by this instance.
Definition datetime.h:351
bool isLeapYear() const
Returns an indication whether the year represented by this instance is a leap year.
Definition datetime.h:426
static constexpr DateTime fromTimeStampGmt(std::time_t timeStamp)
Constructs a new DateTime object with the GMT time from the specified UNIX timeStamp.
Definition datetime.h:274
static DateTime now()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition datetime.h:503
constexpr bool operator>(const DateTime &other) const
Indicates whether a specified DateTime is greater than another specified DateTime.
Definition datetime.h:544
static DateTime fromIsoStringLocal(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.h:266
constexpr bool isNull() const
Returns true if the date represented by the current DateTime class is null.
Definition datetime.h:410
int month() const
Returns the month component of the date represented by this instance.
Definition datetime.h:326
constexpr DateTime()
Constructs a DateTime.
Definition datetime.h:194
DateTime & operator-=(const TimeSpan &timeSpan)
Subtracts a TimeSpan from the current instance.
Definition datetime.h:615
DateTime & operator+=(const TimeSpan &timeSpan)
Adds a TimeSpan to the current instance.
Definition datetime.h:606
static constexpr DateTime unixEpochStart()
Returns the DateTime object for the "1970-01-01T00:00:00Z".
Definition datetime.h:494
static constexpr DateTime fromChronoTimePointGmt(TimePoint timePoint)
Constructs a new DateTime object with the GMT time from the specified std::chrono::time_point.
Definition datetime.h:294
std::uint64_t TickType
Definition datetime.h:57
constexpr int microsecond() const
Returns the microsecond component of the date represented by this instance.
Definition datetime.h:391
constexpr bool operator>=(const DateTime &other) const
Indicates whether a specified DateTime is greater or equal than another specified DateTime.
Definition datetime.h:560
constexpr bool operator!=(const DateTime &other) const
Indicates whether two DateTime instances are not equal.
Definition datetime.h:528
constexpr bool operator==(const DateTime &other) const
Indicates whether two DateTime instances are equal.
Definition datetime.h:520
constexpr DateTime operator+(const TimeSpan &timeSpan) const
Adds another instance.
Definition datetime.h:569
int dayOfYear() const
Returns the day of the year represented by this instance.
Definition datetime.h:342
constexpr bool operator<=(const DateTime &other) const
Indicates whether a specified DateTime is less or equal than another specified DateTime.
Definition datetime.h:552
constexpr bool isSameDay(const DateTime &other) const
Returns and indication whether two DateTime instances represent the same day.
Definition datetime.h:458
constexpr int hour() const
Returns the hour component of the date represented by this instance.
Definition datetime.h:359
static DateTime fromString(const std::string &str)
Parses the given std::string as DateTime.
Definition datetime.h:244
constexpr int second() const
Returns the second component of the date represented by this instance.
Definition datetime.h:375
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)
Constructs a DateTime to the specified year, month, day, hour, minute, second and millisecond.
Definition datetime.h:230
static DateTime fromDate(int year=1, int month=1, int day=1)
Constructs a DateTime to the specified year, month, and day.
Definition datetime.h:211
constexpr TimeSpan timeOfDay() const
Returns the time of day as TimeSpan for this instance.
Definition datetime.h:418
static DateTime fromChronoTimePoint(TimePoint timePoint)
Constructs a new DateTime object with the local time from the specified std::chrono::time_point.
Definition datetime.h:284
constexpr TickType & ticks()
Returns a mutable reference to the total ticks.
Definition datetime.h:302
constexpr TickType totalTicks() const
Returns the number of ticks which represent the value of the current instance.
Definition datetime.h:310
static DateTime gmtNow()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition datetime.h:512
static DateTime fromTimeStamp(std::time_t timeStamp)
Constructs a new DateTime object with the local time from the specified UNIX timeStamp.
Definition datetime.cpp:69
constexpr DateTime operator-(const TimeSpan &timeSpan) const
Subtracts another instance.
Definition datetime.h:578
constexpr bool isEternity() const
Returns whether the instance has the maximal number of ticks.
Definition datetime.h:434
constexpr int millisecond() const
Returns the millisecond component of the date represented by this instance.
Definition datetime.h:383
static DateTime fromTime(int hour=0, int minute=0, int second=0, double millisecond=0.0)
Constructs a DateTime to the specified hour, minute, second and millisecond.
Definition datetime.h:220
constexpr int nanosecond() const
Returns the nanosecond component of the date represented by this instance.
Definition datetime.h:401
static DateTime fromIsoStringGmt(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.h:255
constexpr bool operator<(const DateTime &other) const
Indicates whether a specified DateTime is less than another specified DateTime.
Definition datetime.h:536
static int daysInMonth(int year, int month)
Returns the number of days in the specified month and year.
Definition datetime.h:450
constexpr std::time_t toTimeStamp() const
Returns the UNIX timestamp for the current instance.
Definition datetime.h:478
static constexpr DateTime eternity()
Constructs a new instance of the DateTime class with the maximal number of ticks.
Definition datetime.h:486
constexpr int minute() const
Returns the minute component of the date represented by this instance.
Definition datetime.h:367
int year() const
Returns the year component of the date represented by this instance.
Definition datetime.h:318
Represents a time interval.
Definition timespan.h:25
static constexpr TickType nanosecondsPerTick
Definition timespan.h:99
static constexpr TickType ticksPerMillisecond
Definition timespan.h:101
static constexpr TickType ticksPerMinute
Definition timespan.h:103
static constexpr TickType ticksPerMicrosecond
Definition timespan.h:100
std::int64_t TickType
Definition timespan.h:29
static constexpr TickType ticksPerSecond
Definition timespan.h:102
static constexpr TickType ticksPerDay
Definition timespan.h:105
static constexpr TickType ticksPerHour
Definition timespan.h:104
#define CPP_UTILITIES_MARK_FLAG_ENUM_CLASS(Namespace, EnumClassType)
#define CPP_UTILITIES_EXPORT
Marks the symbol to be exported by the c++utilities library.
Definition global.h:14
Contains all utilities provides by the c++utilities library.
CPP_UTILITIES_EXPORT DateTime operator+(DateTime begin, Period period)
Adds the specified period to the specified date.
Definition period.cpp:60
DatePart
Specifies the date part.
Definition datetime.h:48
bool operator==(const AsHexNumber< T > &lhs, const AsHexNumber< T > &rhs)
Provides operator == required by CPPUNIT_ASSERT_EQUAL.
Definition testutils.h:241
DateTimeParts
The DateTimeParts enum specifies which parts of a timestamp are present.
Definition datetime.h:145
DateTimeOutputFormat
Specifies the output format.
Definition datetime.h:19
DayOfWeek
Specifies the day of the week.
Definition datetime.h:33
STL namespace.
The DateTimeExpression struct holds information about a time expression (e.g.
Definition datetime.h:163
constexpr DateTime gmt() const
Returns the value in UTC time.
Definition datetime.h:178
constexpr bool operator==(const DateTimeExpression &other) const
Returns whether the expressions are equivalent.
Definition datetime.h:186
static DateTimeExpression fromIsoString(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.cpp:388
size_t operator()(const CppUtilities::DateTime &dateTime) const
Definition datetime.h:625