C++ Utilities 5.32.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
42
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;
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
121private:
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
143enum class DateTimeParts : std::uint64_t {
144 None = 0,
145 Year = (1 << 0),
146 Month = (1 << 1),
147 Day = (1 << 2),
148 Hour = (1 << 3),
149 Minute = (1 << 4),
150 Second = (1 << 5),
151 SubSecond = (1 << 6),
152 DeltaHour = (1 << 7),
153 DeltaMinute = (1 << 8),
159};
160
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
177{
178 return value - delta;
179}
180
184constexpr bool DateTimeExpression::operator==(const DateTimeExpression &other) const
185{
186 return value == other.value && delta == other.delta && parts == other.parts;
187}
188
192constexpr inline DateTime::DateTime()
193 : m_ticks(0)
194{
195}
196
201 : m_ticks(ticks)
202{
203}
204
210{
211 return DateTime(dateToTicks(year, month, day));
212}
213
219{
220 return DateTime(timeToTicks(hour, minute, second, millisecond));
221}
222
228inline 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
242inline DateTime DateTime::fromString(const std::string &str)
243{
244 return fromString(str.data());
245}
246
254{
256}
257
265{
267}
268
272constexpr 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
282template <typename TimePoint> inline DateTime DateTime::fromChronoTimePoint(TimePoint timePoint)
283{
284 return DateTime::fromTimeStamp(decltype(timePoint)::clock::to_time_t(timePoint));
285}
286
292template <typename TimePoint> constexpr DateTime DateTime::fromChronoTimePointGmt(TimePoint timePoint)
293{
294 return DateTime::fromTimeStampGmt(decltype(timePoint)::clock::to_time_t(timePoint));
295}
296
301{
302 return m_ticks;
303}
304
309{
310 return m_ticks;
311}
312
316inline int DateTime::year() const
317{
318 return getDatePart(DatePart::Year);
319}
320
324inline int DateTime::month() const
325{
326 return getDatePart(DatePart::Month);
327}
328
332inline int DateTime::day() const
333{
334 return getDatePart(DatePart::Day);
335}
336
340inline int DateTime::dayOfYear() const
341{
342 return getDatePart(DatePart::DayOfYear);
343}
344
349constexpr inline DayOfWeek DateTime::dayOfWeek() const
350{
351 return static_cast<DayOfWeek>((m_ticks / TimeSpan::ticksPerDay) % 7l);
352}
353
357constexpr inline int DateTime::hour() const
358{
359 return static_cast<int>(m_ticks / TimeSpan::ticksPerHour % 24ul);
360}
361
365constexpr inline int DateTime::minute() const
366{
367 return static_cast<int>(m_ticks / TimeSpan::ticksPerMinute % 60ul);
368}
369
373constexpr inline int DateTime::second() const
374{
375 return static_cast<int>(m_ticks / TimeSpan::ticksPerSecond % 60ul);
376}
377
381constexpr inline int DateTime::millisecond() const
382{
383 return static_cast<int>(m_ticks / TimeSpan::ticksPerMillisecond % 1000ul);
384}
385
389constexpr inline int DateTime::microsecond() const
390{
391 return static_cast<int>(m_ticks / TimeSpan::ticksPerMicrosecond % 1000ul);
392}
393
399constexpr inline int DateTime::nanosecond() const
400{
401 return static_cast<int>(m_ticks % 10ul * TimeSpan::nanosecondsPerTick);
402}
403
408constexpr inline bool DateTime::isNull() const
409{
410 return m_ticks == 0;
411}
412
416constexpr inline TimeSpan DateTime::timeOfDay() const
417{
418 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks % TimeSpan::ticksPerDay));
419}
420
424inline bool DateTime::isLeapYear() const
425{
426 return isLeapYear(year());
427}
428
432constexpr inline bool DateTime::isEternity() const
433{
434 return m_ticks == std::numeric_limits<TickType>::max();
435}
436
440constexpr inline bool DateTime::isLeapYear(int year)
441{
442 return (year % 4 != 0) ? false : ((year % 100 == 0) ? (year % 400 == 0) : true);
443}
444
448inline 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
456constexpr inline bool DateTime::isSameDay(const DateTime &other) const
457{
458 return (m_ticks / TimeSpan::ticksPerDay) == (other.m_ticks / TimeSpan::ticksPerDay);
459}
460
466inline std::string DateTime::toString(DateTimeOutputFormat format, bool noMilliseconds) const
467{
468 std::string result;
469 toString(result, format, noMilliseconds);
470 return result;
471}
472
476constexpr std::time_t DateTime::toTimeStamp() const
477{
478 return static_cast<std::time_t>((totalTicks() - DateTime::unixEpochStart().totalTicks()) / TimeSpan::ticksPerSecond);
479}
480
484constexpr inline DateTime DateTime::eternity()
485{
486 return DateTime(std::numeric_limits<TickType>::max());
487}
488
493{
494 return DateTime(621355968000000000);
495}
496
502{
503 return DateTime::fromTimeStamp(std::time(nullptr));
504}
505
511{
512 return DateTime::fromTimeStampGmt(std::time(nullptr));
513}
514
518constexpr inline bool DateTime::operator==(const DateTime &other) const
519{
520 return m_ticks == other.m_ticks;
521}
522
526constexpr inline bool DateTime::operator!=(const DateTime &other) const
527{
528 return m_ticks != other.m_ticks;
529}
530
534constexpr inline bool DateTime::operator<(const DateTime &other) const
535{
536 return m_ticks < other.m_ticks;
537}
538
542constexpr inline bool DateTime::operator>(const DateTime &other) const
543{
544 return m_ticks > other.m_ticks;
545}
546
550constexpr inline bool DateTime::operator<=(const DateTime &other) const
551{
552 return m_ticks <= other.m_ticks;
553}
554
558constexpr inline bool DateTime::operator>=(const DateTime &other) const
559{
560 return m_ticks >= other.m_ticks;
561}
562
567constexpr inline DateTime DateTime::operator+(const TimeSpan &timeSpan) const
568{
569 return DateTime(m_ticks + static_cast<TickType>(timeSpan.m_ticks));
570}
571
576constexpr inline DateTime DateTime::operator-(const TimeSpan &timeSpan) const
577{
578 return DateTime(m_ticks - static_cast<TickType>(timeSpan.m_ticks));
579}
580
585constexpr inline TimeSpan DateTime::operator+(const DateTime &other) const
586{
587 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks + other.m_ticks));
588}
589
596constexpr inline TimeSpan DateTime::operator-(const DateTime &other) const
597{
598 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks - other.m_ticks));
599}
600
604inline DateTime &DateTime::operator+=(const TimeSpan &timeSpan)
605{
606 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
607 return *this;
608}
609
613inline DateTime &DateTime::operator-=(const TimeSpan &timeSpan)
614{
615 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
616 return *this;
617}
618} // namespace CppUtilities
619
620namespace std {
622template <> 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
631
632#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:466
int day() const
Returns the day component of the date represented by this instance.
Definition datetime.h:332
constexpr DayOfWeek dayOfWeek() const
Returns the day of the week represented by this instance.
Definition datetime.h:349
std::string toIsoStringWithCustomDelimiters(TimeSpan timeZoneDelta=TimeSpan(), char dateDelimiter='-', char timeDelimiter=':', char timeZoneDelimiter=':') const
Returns the string representation of the current instance in the ISO format with custom delimiters,...
Definition datetime.cpp:195
bool isLeapYear() const
Returns an indication whether the year represented by this instance is a leap year.
Definition datetime.h:424
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:272
static DateTime now()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition datetime.h:501
constexpr bool operator>(const DateTime &other) const
Indicates whether a specified DateTime is greater than another specified DateTime.
Definition datetime.h:542
static DateTime fromIsoStringLocal(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.h:264
constexpr bool isNull() const
Returns true if the date represented by the current DateTime class is null.
Definition datetime.h:408
int month() const
Returns the month component of the date represented by this instance.
Definition datetime.h:324
constexpr DateTime()
Constructs a DateTime.
Definition datetime.h:192
DateTime & operator-=(const TimeSpan &timeSpan)
Subtracts a TimeSpan from the current instance.
Definition datetime.h:613
DateTime & operator+=(const TimeSpan &timeSpan)
Adds a TimeSpan to the current instance.
Definition datetime.h:604
std::string toIsoString(TimeSpan timeZoneDelta=TimeSpan()) const
Returns the string representation of the current instance in the ISO format, eg.
Definition datetime.cpp:229
static constexpr DateTime unixEpochStart()
Returns the DateTime object for the "1970-01-01T00:00:00Z".
Definition datetime.h:492
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:292
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:389
constexpr bool operator>=(const DateTime &other) const
Indicates whether a specified DateTime is greater or equal than another specified DateTime.
Definition datetime.h:558
constexpr bool operator!=(const DateTime &other) const
Indicates whether two DateTime instances are not equal.
Definition datetime.h:526
constexpr bool operator==(const DateTime &other) const
Indicates whether two DateTime instances are equal.
Definition datetime.h:518
static std::pair< DateTime, TimeSpan > fromIsoString(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.cpp:112
constexpr DateTime operator+(const TimeSpan &timeSpan) const
Adds another instance.
Definition datetime.h:567
int dayOfYear() const
Returns the day of the year represented by this instance.
Definition datetime.h:340
static DateTime exactGmtNow()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition datetime.cpp:284
constexpr bool operator<=(const DateTime &other) const
Indicates whether a specified DateTime is less or equal than another specified DateTime.
Definition datetime.h:550
constexpr bool isSameDay(const DateTime &other) const
Returns and indication whether two DateTime instances represent the same day.
Definition datetime.h:456
constexpr int hour() const
Returns the hour component of the date represented by this instance.
Definition datetime.h:357
static DateTime fromString(const std::string &str)
Parses the given std::string as DateTime.
Definition datetime.h:242
constexpr int second() const
Returns the second component of the date represented by this instance.
Definition datetime.h:373
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:228
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:209
constexpr TimeSpan timeOfDay() const
Returns the time of day as TimeSpan for this instance.
Definition datetime.h:416
static DateTime fromChronoTimePoint(TimePoint timePoint)
Constructs a new DateTime object with the local time from the specified std::chrono::time_point.
Definition datetime.h:282
constexpr TickType & ticks()
Returns a mutable reference to the total ticks.
Definition datetime.h:300
constexpr TickType totalTicks() const
Returns the number of ticks which represent the value of the current instance.
Definition datetime.h:308
static DateTime gmtNow()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition datetime.h:510
static DateTime fromTimeStamp(std::time_t timeStamp)
Constructs a new DateTime object with the local time from the specified UNIX timeStamp.
Definition datetime.cpp:76
constexpr DateTime operator-(const TimeSpan &timeSpan) const
Subtracts another instance.
Definition datetime.h:576
constexpr bool isEternity() const
Returns whether the instance has the maximal number of ticks.
Definition datetime.h:432
constexpr int millisecond() const
Returns the millisecond component of the date represented by this instance.
Definition datetime.h:381
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:218
static const char * printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation=false)
Returns the string representation as C-style string for the given day of week.
Definition datetime.cpp:241
constexpr int nanosecond() const
Returns the nanosecond component of the date represented by this instance.
Definition datetime.h:399
static DateTime fromIsoStringGmt(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.h:253
constexpr bool operator<(const DateTime &other) const
Indicates whether a specified DateTime is less than another specified DateTime.
Definition datetime.h:534
static int daysInMonth(int year, int month)
Returns the number of days in the specified month and year.
Definition datetime.h:448
constexpr std::time_t toTimeStamp() const
Returns the UNIX timestamp for the current instance.
Definition datetime.h:476
static constexpr DateTime eternity()
Constructs a new instance of the DateTime class with the maximal number of ticks.
Definition datetime.h:484
constexpr int minute() const
Returns the minute component of the date represented by this instance.
Definition datetime.h:365
int year() const
Returns the year component of the date represented by this instance.
Definition datetime.h:316
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 provided by the c++utilities library.
DatePart
Specifies the date part.
Definition datetime.h:48
DateTimeParts
The DateTimeParts enum specifies which parts of a timestamp are present.
Definition datetime.h:143
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:161
constexpr DateTime gmt() const
Returns the value in UTC time.
Definition datetime.h:176
constexpr bool operator==(const DateTimeExpression &other) const
Returns whether the expressions are equivalent.
Definition datetime.h:184
static DateTimeExpression fromString(const char *str)
Parses the given C-style string.
Definition datetime.cpp:499
std::string toIsoString(char dateDelimiter='-', char timeDelimiter=':', char timeZoneDelimiter=':') const
Returns the string representation of the current instance in the ISO format.
Definition datetime.cpp:544
static DateTimeExpression fromIsoString(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.cpp:399
size_t operator()(const CppUtilities::DateTime &dateTime) const
Definition datetime.h:623