C++ Utilities 5.16.0
Useful C++ classes and routines such as argument parser, IO and conversion utilities
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
6#include <cstdint>
7#include <ctime>
8#include <limits>
9#include <string>
10
11namespace CppUtilities {
12
19 DateOnly,
20 TimeOnly,
23 Iso,
25};
26
31enum class DayOfWeek {
32 Monday,
33 Tuesday,
34 Wednesday,
35 Thursday,
36 Friday,
37 Saturday,
38 Sunday
39};
40
46enum class DatePart {
47 Year,
48 Month,
49 DayOfYear,
50 Day
51};
52
54public:
55 using TickType = std::uint64_t;
56
57 explicit constexpr DateTime();
58 explicit constexpr DateTime(TickType ticks);
59 static DateTime fromDate(int year = 1, int month = 1, int day = 1);
60 static DateTime fromTime(int hour = 0, int minute = 0, int second = 0, double millisecond = 0.0);
61 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);
62 static DateTime fromString(const std::string &str);
63 static DateTime fromString(const char *str);
64 static std::pair<DateTime, TimeSpan> fromIsoString(const char *str);
65 static DateTime fromIsoStringGmt(const char *str);
66 static DateTime fromIsoStringLocal(const char *str);
67 static DateTime fromTimeStamp(std::time_t timeStamp);
68 constexpr static DateTime fromTimeStampGmt(std::time_t timeStamp);
69 template <typename TimePoint> static DateTime fromChronoTimePoint(TimePoint timePoint);
70 template <typename TimePoint> constexpr static DateTime fromChronoTimePointGmt(TimePoint timePoint);
71
72 constexpr TickType &ticks();
73 constexpr TickType totalTicks() const;
74 int year() const;
75 int month() const;
76 int day() const;
77 int dayOfYear() const;
78 constexpr DayOfWeek dayOfWeek() const;
79 constexpr int hour() const;
80 constexpr int minute() const;
81 constexpr int second() const;
82 constexpr int millisecond() const;
83 constexpr int microsecond() const;
84 constexpr int nanosecond() const;
85 constexpr bool isNull() const;
86 constexpr TimeSpan timeOfDay() const;
87 bool isLeapYear() const;
88 constexpr bool isEternity() const;
89 constexpr bool isSameDay(const DateTime &other) const;
90 std::string toString(DateTimeOutputFormat format = DateTimeOutputFormat::DateAndTime, bool noMilliseconds = false) const;
91 void toString(std::string &result, DateTimeOutputFormat format = DateTimeOutputFormat::DateAndTime, bool noMilliseconds = false) const;
92 std::string toIsoStringWithCustomDelimiters(
93 TimeSpan timeZoneDelta = TimeSpan(), char dateDelimiter = '-', char timeDelimiter = ':', char timeZoneDelimiter = ':') const;
94 std::string toIsoString(TimeSpan timeZoneDelta = TimeSpan()) const;
95 constexpr std::time_t toTimeStamp() const;
96 static const char *printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation = false);
97
98 static constexpr DateTime eternity();
99 static constexpr DateTime unixEpochStart();
100 static DateTime now();
101 static DateTime gmtNow();
102#if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
103 static DateTime exactGmtNow();
104#endif
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
143constexpr inline DateTime::DateTime()
144 : m_ticks(0)
145{
146}
147
151constexpr inline DateTime::DateTime(TickType ticks)
152 : m_ticks(ticks)
153{
154}
155
160inline DateTime DateTime::fromDate(int year, int month, int day)
161{
162 return DateTime(dateToTicks(year, month, day));
163}
164
169inline DateTime DateTime::fromTime(int hour, int minute, int second, double millisecond)
170{
171 return DateTime(timeToTicks(hour, minute, second, millisecond));
172}
173
179inline DateTime DateTime::fromDateAndTime(int year, int month, int day, int hour, int minute, int second, double millisecond)
180{
181 return DateTime(dateToTicks(year, month, day) + timeToTicks(hour, minute, second, millisecond));
182}
183
193inline DateTime DateTime::fromString(const std::string &str)
194{
195 return fromString(str.data());
196}
197
205{
206 const auto tmp = fromIsoString(str);
207 return tmp.first - tmp.second;
208}
209
217{
218 return fromIsoString(str).first;
219}
220
224constexpr inline DateTime DateTime::fromTimeStampGmt(std::time_t timeStamp)
225{
226 return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(timeStamp) * TimeSpan::ticksPerSecond);
227}
228
234template <typename TimePoint> inline DateTime DateTime::fromChronoTimePoint(TimePoint timePoint)
235{
236 return DateTime::fromTimeStamp(decltype(timePoint)::clock::to_time_t(timePoint));
237}
238
244template <typename TimePoint> constexpr DateTime DateTime::fromChronoTimePointGmt(TimePoint timePoint)
245{
246 return DateTime::fromTimeStampGmt(decltype(timePoint)::clock::to_time_t(timePoint));
247}
248
253{
254 return m_ticks;
255}
256
261{
262 return m_ticks;
263}
264
268inline int DateTime::year() const
269{
270 return getDatePart(DatePart::Year);
271}
272
276inline int DateTime::month() const
277{
278 return getDatePart(DatePart::Month);
279}
280
284inline int DateTime::day() const
285{
286 return getDatePart(DatePart::Day);
287}
288
292inline int DateTime::dayOfYear() const
293{
294 return getDatePart(DatePart::DayOfYear);
295}
296
301constexpr inline DayOfWeek DateTime::dayOfWeek() const
302{
303 return static_cast<DayOfWeek>((m_ticks / TimeSpan::ticksPerDay) % 7l);
304}
305
309constexpr inline int DateTime::hour() const
310{
311 return static_cast<int>(m_ticks / TimeSpan::ticksPerHour % 24ul);
312}
313
317constexpr inline int DateTime::minute() const
318{
319 return static_cast<int>(m_ticks / TimeSpan::ticksPerMinute % 60ul);
320}
321
325constexpr inline int DateTime::second() const
326{
327 return static_cast<int>(m_ticks / TimeSpan::ticksPerSecond % 60ul);
328}
329
333constexpr inline int DateTime::millisecond() const
334{
335 return static_cast<int>(m_ticks / TimeSpan::ticksPerMillisecond % 1000ul);
336}
337
341constexpr inline int DateTime::microsecond() const
342{
343 return static_cast<int>(m_ticks / TimeSpan::ticksPerMicrosecond % 1000ul);
344}
345
351constexpr inline int DateTime::nanosecond() const
352{
353 return static_cast<int>(m_ticks % 10ul * TimeSpan::nanosecondsPerTick);
354}
355
360constexpr inline bool DateTime::isNull() const
361{
362 return m_ticks == 0;
363}
364
368constexpr inline TimeSpan DateTime::timeOfDay() const
369{
370 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks % TimeSpan::ticksPerDay));
371}
372
376inline bool DateTime::isLeapYear() const
377{
378 return isLeapYear(year());
379}
380
384constexpr inline bool DateTime::isEternity() const
385{
386 return m_ticks == std::numeric_limits<TickType>::max();
387}
388
392constexpr inline bool DateTime::isLeapYear(int year)
393{
394 return (year % 4 != 0) ? false : ((year % 100 == 0) ? (year % 400 == 0) : true);
395}
396
400inline int DateTime::daysInMonth(int year, int month)
401{
402 return (month >= 1 && month <= 12) ? (isLeapYear(year) ? m_daysInMonth366[month - 1] : m_daysInMonth365[month - 1]) : (0);
403}
404
408constexpr inline bool DateTime::isSameDay(const DateTime &other) const
409{
410 return (m_ticks / TimeSpan::ticksPerDay) == (other.m_ticks / TimeSpan::ticksPerDay);
411}
412
418inline std::string DateTime::toString(DateTimeOutputFormat format, bool noMilliseconds) const
419{
420 std::string result;
421 toString(result, format, noMilliseconds);
422 return result;
423}
424
428constexpr std::time_t DateTime::toTimeStamp() const
429{
430 return static_cast<std::time_t>((totalTicks() - DateTime::unixEpochStart().totalTicks()) / TimeSpan::ticksPerSecond);
431}
432
436constexpr inline DateTime DateTime::eternity()
437{
439}
440
445{
446 return DateTime(621355968000000000);
447}
448
454{
455 return DateTime::fromTimeStamp(std::time(nullptr));
456}
457
463{
464 return DateTime::fromTimeStampGmt(std::time(nullptr));
465}
466
470constexpr inline bool DateTime::operator==(const DateTime &other) const
471{
472 return m_ticks == other.m_ticks;
473}
474
478constexpr inline bool DateTime::operator!=(const DateTime &other) const
479{
480 return m_ticks != other.m_ticks;
481}
482
486constexpr inline bool DateTime::operator<(const DateTime &other) const
487{
488 return m_ticks < other.m_ticks;
489}
490
494constexpr inline bool DateTime::operator>(const DateTime &other) const
495{
496 return m_ticks > other.m_ticks;
497}
498
502constexpr inline bool DateTime::operator<=(const DateTime &other) const
503{
504 return m_ticks <= other.m_ticks;
505}
506
510constexpr inline bool DateTime::operator>=(const DateTime &other) const
511{
512 return m_ticks >= other.m_ticks;
513}
514
519constexpr inline DateTime DateTime::operator+(const TimeSpan &timeSpan) const
520{
521 return DateTime(m_ticks + static_cast<TickType>(timeSpan.m_ticks));
522}
523
528constexpr inline DateTime DateTime::operator-(const TimeSpan &timeSpan) const
529{
530 return DateTime(m_ticks - static_cast<TickType>(timeSpan.m_ticks));
531}
532
537constexpr inline TimeSpan DateTime::operator+(const DateTime &other) const
538{
539 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks + other.m_ticks));
540}
541
548constexpr inline TimeSpan DateTime::operator-(const DateTime &other) const
549{
550 return TimeSpan(static_cast<TimeSpan::TickType>(m_ticks - other.m_ticks));
551}
552
556inline DateTime &DateTime::operator+=(const TimeSpan &timeSpan)
557{
558 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
559 return *this;
560}
561
565inline DateTime &DateTime::operator-=(const TimeSpan &timeSpan)
566{
567 m_ticks += static_cast<TickType>(timeSpan.m_ticks);
568 return *this;
569}
570} // namespace CppUtilities
571
572namespace std {
574template <> struct hash<CppUtilities::DateTime> {
575 inline size_t operator()(const CppUtilities::DateTime &dateTime) const
576 {
577 return hash<CppUtilities::DateTime::TickType>()(dateTime.totalTicks());
578 }
579};
580} // namespace std
581
582#endif // CHRONO_UTILITIES_DATETIME_H
Represents an instant in time, typically expressed as a date and time of day.
Definition: datetime.h:53
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:418
int day() const
Returns the day component of the date represented by this instance.
Definition: datetime.h:284
constexpr DayOfWeek dayOfWeek() const
Returns the day of the week represented by this instance.
Definition: datetime.h:301
bool isLeapYear() const
Returns an indication whether the year represented by this instance is a leap year.
Definition: datetime.h:376
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:224
static DateTime now()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition: datetime.h:453
constexpr bool operator>(const DateTime &other) const
Indicates whether a specified DateTime is greater than another specified DateTime.
Definition: datetime.h:494
static DateTime fromIsoStringLocal(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition: datetime.h:216
constexpr bool isNull() const
Returns true if the date represented by the current DateTime class is null.
Definition: datetime.h:360
int month() const
Returns the month component of the date represented by this instance.
Definition: datetime.h:276
constexpr DateTime()
Constructs a DateTime.
Definition: datetime.h:143
DateTime & operator-=(const TimeSpan &timeSpan)
Subtracts a TimeSpan from the current instance.
Definition: datetime.h:565
DateTime & operator+=(const TimeSpan &timeSpan)
Adds a TimeSpan to the current instance.
Definition: datetime.h:556
static constexpr DateTime unixEpochStart()
Returns the DateTime object for the "1970-01-01T00:00:00Z".
Definition: datetime.h:444
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:244
std::uint64_t TickType
Definition: datetime.h:55
constexpr int microsecond() const
Returns the microsecond component of the date represented by this instance.
Definition: datetime.h:341
constexpr bool operator>=(const DateTime &other) const
Indicates whether a specified DateTime is greater or equal than another specified DateTime.
Definition: datetime.h:510
constexpr bool operator!=(const DateTime &other) const
Indicates whether two DateTime instances are not equal.
Definition: datetime.h:478
constexpr bool operator==(const DateTime &other) const
Indicates whether two DateTime instances are equal.
Definition: datetime.h:470
static std::pair< DateTime, TimeSpan > fromIsoString(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition: datetime.cpp:120
constexpr DateTime operator+(const TimeSpan &timeSpan) const
Adds another instance.
Definition: datetime.h:519
int dayOfYear() const
Returns the day of the year represented by this instance.
Definition: datetime.h:292
constexpr bool operator<=(const DateTime &other) const
Indicates whether a specified DateTime is less or equal than another specified DateTime.
Definition: datetime.h:502
constexpr bool isSameDay(const DateTime &other) const
Returns and indication whether two DateTime instances represent the same day.
Definition: datetime.h:408
constexpr int hour() const
Returns the hour component of the date represented by this instance.
Definition: datetime.h:309
static DateTime fromString(const std::string &str)
Parses the given std::string as DateTime.
Definition: datetime.h:193
constexpr int second() const
Returns the second component of the date represented by this instance.
Definition: datetime.h:325
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:179
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:160
constexpr TimeSpan timeOfDay() const
Returns the time of day as TimeSpan for this instance.
Definition: datetime.h:368
static DateTime fromChronoTimePoint(TimePoint timePoint)
Constructs a new DateTime object with the local time from the specified std::chrono::time_point.
Definition: datetime.h:234
constexpr TickType & ticks()
Returns a mutable reference to the total ticks.
Definition: datetime.h:252
constexpr TickType totalTicks() const
Returns the number of ticks which represent the value of the current instance.
Definition: datetime.h:260
static DateTime gmtNow()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition: datetime.h:462
static DateTime fromTimeStamp(std::time_t timeStamp)
Constructs a new DateTime object with the local time from the specified UNIX timeStamp.
Definition: datetime.cpp:59
constexpr DateTime operator-(const TimeSpan &timeSpan) const
Subtracts another instance.
Definition: datetime.h:528
constexpr bool isEternity() const
Returns whether the instance has the maximal number of ticks.
Definition: datetime.h:384
constexpr int millisecond() const
Returns the millisecond component of the date represented by this instance.
Definition: datetime.h:333
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:169
constexpr int nanosecond() const
Returns the nanosecond component of the date represented by this instance.
Definition: datetime.h:351
static DateTime fromIsoStringGmt(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition: datetime.h:204
constexpr bool operator<(const DateTime &other) const
Indicates whether a specified DateTime is less than another specified DateTime.
Definition: datetime.h:486
static int daysInMonth(int year, int month)
Returns the number of days in the specified month and year.
Definition: datetime.h:400
constexpr std::time_t toTimeStamp() const
Returns the UNIX timestamp for the current instance.
Definition: datetime.h:428
static constexpr DateTime eternity()
Constructs a new instance of the DateTime class with the maximal number of ticks.
Definition: datetime.h:436
constexpr int minute() const
Returns the minute component of the date represented by this instance.
Definition: datetime.h:317
int year() const
Returns the year component of the date represented by this instance.
Definition: datetime.h:268
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_EXPORT
Marks the symbol to be exported by the c++utilities library.
constexpr FlagEnumClass & operator-=(FlagEnumClass &lhs, FlagEnumClass rhs)
Definition: flagenumclass.h:71
constexpr FlagEnumClass & operator+=(FlagEnumClass &lhs, FlagEnumClass rhs)
Definition: flagenumclass.h:64
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:46
bool operator==(const AsHexNumber< T > &lhs, const AsHexNumber< T > &rhs)
Provides operator == required by CPPUNIT_ASSERT_EQUAL.
Definition: testutils.h:230
constexpr T max(T first, T second)
Returns the greatest of the given items.
Definition: math.h:100
DateTimeOutputFormat
Specifies the output format.
Definition: datetime.h:17
DayOfWeek
Specifies the day of the week.
Definition: datetime.h:31
STL namespace.
size_t operator()(const CppUtilities::DateTime &dateTime) const
Definition: datetime.h:575