C++ Utilities  5.10.5
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 
11 namespace CppUtilities {
12 
18  DateAndTime,
19  DateOnly,
20  TimeOnly,
23  Iso,
25 };
26 
31 enum class DayOfWeek {
32  Monday,
33  Tuesday,
34  Wednesday,
35  Thursday,
36  Friday,
37  Saturday,
38  Sunday
39 };
40 
46 enum class DatePart {
47  Year,
48  Month,
49  DayOfYear,
50  Day
51 };
52 
54 public:
55  explicit constexpr DateTime();
56  explicit constexpr DateTime(std::uint64_t ticks);
57  static DateTime fromDate(int year = 1, int month = 1, int day = 1);
58  static DateTime fromTime(int hour = 0, int minute = 0, int second = 0, double millisecond = 0.0);
59  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);
60  static DateTime fromString(const std::string &str);
61  static DateTime fromString(const char *str);
62  static std::pair<DateTime, TimeSpan> fromIsoString(const char *str);
63  static DateTime fromIsoStringGmt(const char *str);
64  static DateTime fromIsoStringLocal(const char *str);
65  static DateTime fromTimeStamp(std::time_t timeStamp);
66  constexpr static DateTime fromTimeStampGmt(std::time_t timeStamp);
67  template <typename TimePoint> static DateTime fromChronoTimePoint(TimePoint timePoint);
68  template <typename TimePoint> constexpr static DateTime fromChronoTimePointGmt(TimePoint timePoint);
69 
70  constexpr std::uint64_t &ticks();
71  constexpr std::uint64_t totalTicks() const;
72  int year() const;
73  int month() const;
74  int day() const;
75  int dayOfYear() const;
76  constexpr DayOfWeek dayOfWeek() const;
77  constexpr int hour() const;
78  constexpr int minute() const;
79  constexpr int second() const;
80  constexpr int millisecond() const;
81  constexpr int microsecond() const;
82  constexpr int nanosecond() const;
83  constexpr bool isNull() const;
84  constexpr TimeSpan timeOfDay() const;
85  bool isLeapYear() const;
86  constexpr bool isEternity() const;
87  constexpr bool isSameDay(const DateTime &other) const;
88  std::string toString(DateTimeOutputFormat format = DateTimeOutputFormat::DateAndTime, bool noMilliseconds = false) const;
89  void toString(std::string &result, DateTimeOutputFormat format = DateTimeOutputFormat::DateAndTime, bool noMilliseconds = false) const;
90  std::string toIsoStringWithCustomDelimiters(
91  TimeSpan timeZoneDelta = TimeSpan(), char dateDelimiter = '-', char timeDelimiter = ':', char timeZoneDelimiter = ':') const;
92  std::string toIsoString(TimeSpan timeZoneDelta = TimeSpan()) const;
93  constexpr std::time_t toTimeStamp() const;
94  static const char *printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation = false);
95 
96  static constexpr DateTime eternity();
97  static constexpr DateTime unixEpochStart();
98  static DateTime now();
99  static DateTime gmtNow();
100 #if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
101  static DateTime exactGmtNow();
102 #endif
103  constexpr static bool isLeapYear(int year);
104  static int daysInMonth(int year, int month);
105 
106  constexpr bool operator==(const DateTime &other) const;
107  constexpr bool operator!=(const DateTime &other) const;
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 DateTime operator+(const TimeSpan &timeSpan) const;
113  constexpr DateTime operator-(const TimeSpan &timeSpan) const;
114  constexpr TimeSpan operator+(const DateTime &other) const;
115  constexpr TimeSpan operator-(const DateTime &other) const;
116  DateTime &operator+=(const TimeSpan &timeSpan);
117  DateTime &operator-=(const TimeSpan &timeSpan);
118 
119 private:
120  static std::uint64_t dateToTicks(int year, int month, int day);
121  static std::uint64_t timeToTicks(int hour, int minute, int second, double millisecond);
122  int getDatePart(DatePart part) const;
123 
124  std::uint64_t m_ticks;
125  static const int m_daysPerYear;
126  static const int m_daysPer4Years;
127  static const int m_daysPer100Years;
128  static const int m_daysPer400Years;
129  static const int m_daysTo1601;
130  static const int m_daysTo1899;
131  static const int m_daysTo10000;
132  static const int m_daysToMonth365[13];
133  static const int m_daysToMonth366[13];
134  static const int m_daysInMonth365[12];
135  static const int m_daysInMonth366[12];
136 };
137 
141 constexpr inline DateTime::DateTime()
142  : m_ticks(0)
143 {
144 }
145 
149 constexpr inline DateTime::DateTime(std::uint64_t ticks)
150  : m_ticks(ticks)
151 {
152 }
153 
158 inline DateTime DateTime::fromDate(int year, int month, int day)
159 {
160  return DateTime(dateToTicks(year, month, day));
161 }
162 
167 inline DateTime DateTime::fromTime(int hour, int minute, int second, double millisecond)
168 {
169  return DateTime(timeToTicks(hour, minute, second, millisecond));
170 }
171 
177 inline DateTime DateTime::fromDateAndTime(int year, int month, int day, int hour, int minute, int second, double millisecond)
178 {
179  return DateTime(dateToTicks(year, month, day) + timeToTicks(hour, minute, second, millisecond));
180 }
181 
191 inline DateTime DateTime::fromString(const std::string &str)
192 {
193  return fromString(str.data());
194 }
195 
202 inline DateTime DateTime::fromIsoStringGmt(const char *str)
203 {
204  const auto tmp = fromIsoString(str);
205  return tmp.first - tmp.second;
206 }
207 
214 inline DateTime DateTime::fromIsoStringLocal(const char *str)
215 {
216  return fromIsoString(str).first;
217 }
218 
222 constexpr inline DateTime DateTime::fromTimeStampGmt(std::time_t timeStamp)
223 {
224  return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(timeStamp) * TimeSpan::ticksPerSecond);
225 }
226 
232 template <typename TimePoint> inline DateTime DateTime::fromChronoTimePoint(TimePoint timePoint)
233 {
234  return DateTime::fromTimeStamp(decltype(timePoint)::clock::to_time_t(timePoint));
235 }
236 
242 template <typename TimePoint> constexpr DateTime DateTime::fromChronoTimePointGmt(TimePoint timePoint)
243 {
244  return DateTime::fromTimeStampGmt(decltype(timePoint)::clock::to_time_t(timePoint));
245 }
246 
250 constexpr inline std::uint64_t &DateTime::ticks()
251 {
252  return m_ticks;
253 }
254 
258 constexpr inline std::uint64_t DateTime::totalTicks() const
259 {
260  return m_ticks;
261 }
262 
266 inline int DateTime::year() const
267 {
268  return getDatePart(DatePart::Year);
269 }
270 
274 inline int DateTime::month() const
275 {
276  return getDatePart(DatePart::Month);
277 }
278 
282 inline int DateTime::day() const
283 {
284  return getDatePart(DatePart::Day);
285 }
286 
290 inline int DateTime::dayOfYear() const
291 {
292  return getDatePart(DatePart::DayOfYear);
293 }
294 
299 constexpr inline DayOfWeek DateTime::dayOfWeek() const
300 {
301  return static_cast<DayOfWeek>((m_ticks / TimeSpan::ticksPerDay) % 7l);
302 }
303 
307 constexpr inline int DateTime::hour() const
308 {
309  return static_cast<int>(m_ticks / TimeSpan::ticksPerHour % 24ul);
310 }
311 
315 constexpr inline int DateTime::minute() const
316 {
317  return static_cast<int>(m_ticks / TimeSpan::ticksPerMinute % 60ul);
318 }
319 
323 constexpr inline int DateTime::second() const
324 {
325  return static_cast<int>(m_ticks / TimeSpan::ticksPerSecond % 60ul);
326 }
327 
331 constexpr inline int DateTime::millisecond() const
332 {
333  return static_cast<int>(m_ticks / TimeSpan::ticksPerMillisecond % 1000ul);
334 }
335 
339 constexpr inline int DateTime::microsecond() const
340 {
341  return static_cast<int>(m_ticks / TimeSpan::ticksPerMicrosecond % 1000ul);
342 }
343 
349 constexpr inline int DateTime::nanosecond() const
350 {
351  return static_cast<int>(m_ticks % 10ul * TimeSpan::nanosecondsPerTick);
352 }
353 
358 constexpr inline bool DateTime::isNull() const
359 {
360  return m_ticks == 0;
361 }
362 
366 constexpr inline TimeSpan DateTime::timeOfDay() const
367 {
368  return TimeSpan(static_cast<std::int64_t>(m_ticks % TimeSpan::ticksPerDay));
369 }
370 
374 inline bool DateTime::isLeapYear() const
375 {
376  return isLeapYear(year());
377 }
378 
382 constexpr inline bool DateTime::isEternity() const
383 {
384  return m_ticks == std::numeric_limits<decltype(m_ticks)>::max();
385 }
386 
390 constexpr inline bool DateTime::isLeapYear(int year)
391 {
392  return (year % 4 != 0) ? false : ((year % 100 == 0) ? (year % 400 == 0) : true);
393 }
394 
398 inline int DateTime::daysInMonth(int year, int month)
399 {
400  return (month >= 1 && month <= 12) ? (isLeapYear(year) ? m_daysInMonth366[month - 1] : m_daysInMonth365[month - 1]) : (0);
401 }
402 
406 constexpr inline bool DateTime::isSameDay(const DateTime &other) const
407 {
408  return (m_ticks / TimeSpan::ticksPerDay) == (other.m_ticks / TimeSpan::ticksPerDay);
409 }
410 
416 inline std::string DateTime::toString(DateTimeOutputFormat format, bool noMilliseconds) const
417 {
418  std::string result;
419  toString(result, format, noMilliseconds);
420  return result;
421 }
422 
426 constexpr std::time_t DateTime::toTimeStamp() const
427 {
428  return static_cast<std::time_t>((totalTicks() - DateTime::unixEpochStart().totalTicks()) / TimeSpan::ticksPerSecond);
429 }
430 
434 constexpr inline DateTime DateTime::eternity()
435 {
436  return DateTime(std::numeric_limits<decltype(m_ticks)>::max());
437 }
438 
443 {
444  return DateTime(621355968000000000);
445 }
446 
452 {
453  return DateTime::fromTimeStamp(std::time(nullptr));
454 }
455 
461 {
462  return DateTime::fromTimeStampGmt(std::time(nullptr));
463 }
464 
468 constexpr inline bool DateTime::operator==(const DateTime &other) const
469 {
470  return m_ticks == other.m_ticks;
471 }
472 
476 constexpr inline bool DateTime::operator!=(const DateTime &other) const
477 {
478  return m_ticks != other.m_ticks;
479 }
480 
484 constexpr inline bool DateTime::operator<(const DateTime &other) const
485 {
486  return m_ticks < other.m_ticks;
487 }
488 
492 constexpr inline bool DateTime::operator>(const DateTime &other) const
493 {
494  return m_ticks > other.m_ticks;
495 }
496 
500 constexpr inline bool DateTime::operator<=(const DateTime &other) const
501 {
502  return m_ticks <= other.m_ticks;
503 }
504 
508 constexpr inline bool DateTime::operator>=(const DateTime &other) const
509 {
510  return m_ticks >= other.m_ticks;
511 }
512 
517 constexpr inline DateTime DateTime::operator+(const TimeSpan &timeSpan) const
518 {
519  return DateTime(m_ticks + static_cast<std::uint64_t>(timeSpan.m_ticks));
520 }
521 
526 constexpr inline DateTime DateTime::operator-(const TimeSpan &timeSpan) const
527 {
528  return DateTime(m_ticks - static_cast<std::uint64_t>(timeSpan.m_ticks));
529 }
530 
535 constexpr inline TimeSpan DateTime::operator+(const DateTime &other) const
536 {
537  return TimeSpan(static_cast<std::int64_t>(m_ticks + other.m_ticks));
538 }
539 
546 constexpr inline TimeSpan DateTime::operator-(const DateTime &other) const
547 {
548  return TimeSpan(static_cast<std::int64_t>(m_ticks - other.m_ticks));
549 }
550 
554 inline DateTime &DateTime::operator+=(const TimeSpan &timeSpan)
555 {
556  m_ticks += static_cast<std::uint64_t>(timeSpan.m_ticks);
557  return *this;
558 }
559 
563 inline DateTime &DateTime::operator-=(const TimeSpan &timeSpan)
564 {
565  m_ticks += static_cast<std::uint64_t>(timeSpan.m_ticks);
566  return *this;
567 }
568 } // namespace CppUtilities
569 
570 namespace std {
572 template <> struct hash<CppUtilities::DateTime> {
573  inline size_t operator()(const CppUtilities::DateTime &dateTime) const
574  {
575  return hash<decltype(dateTime.totalTicks())>()(dateTime.totalTicks());
576  }
577 };
578 } // namespace std
579 
580 #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:416
int day() const
Returns the day component of the date represented by this instance.
Definition: datetime.h:282
constexpr DayOfWeek dayOfWeek() const
Returns the day of the week represented by this instance.
Definition: datetime.h:299
bool isLeapYear() const
Returns an indication whether the year represented by this instance is a leap year.
Definition: datetime.h:374
constexpr static DateTime fromTimeStampGmt(std::time_t timeStamp)
Constructs a new DateTime object with the GMT time from the specified UNIX timeStamp.
Definition: datetime.h:222
static DateTime now()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition: datetime.h:451
constexpr bool operator>(const DateTime &other) const
Indicates whether a specified DateTime is greater than another specified DateTime.
Definition: datetime.h:492
static DateTime fromIsoStringLocal(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition: datetime.h:214
constexpr bool isNull() const
Returns true if the date represented by the current DateTime class is null.
Definition: datetime.h:358
int month() const
Returns the month component of the date represented by this instance.
Definition: datetime.h:274
constexpr std::uint64_t totalTicks() const
Returns the number of ticks which represent the value of the current instance.
Definition: datetime.h:258
constexpr DateTime()
Constructs a DateTime.
Definition: datetime.h:141
DateTime & operator-=(const TimeSpan &timeSpan)
Subtracts a TimeSpan from the current instance.
Definition: datetime.h:563
DateTime & operator+=(const TimeSpan &timeSpan)
Adds a TimeSpan to the current instance.
Definition: datetime.h:554
static constexpr DateTime unixEpochStart()
Returns the DateTime object for the "1970-01-01T00:00:00Z".
Definition: datetime.h:442
constexpr int microsecond() const
Returns the microsecond component of the date represented by this instance.
Definition: datetime.h:339
constexpr bool operator>=(const DateTime &other) const
Indicates whether a specified DateTime is greater or equal than another specified DateTime.
Definition: datetime.h:508
constexpr bool operator!=(const DateTime &other) const
Indicates whether two DateTime instances are not equal.
Definition: datetime.h:476
constexpr bool operator==(const DateTime &other) const
Indicates whether two DateTime instances are equal.
Definition: datetime.h:468
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:517
int dayOfYear() const
Returns the day of the year represented by this instance.
Definition: datetime.h:290
constexpr bool operator<=(const DateTime &other) const
Indicates whether a specified DateTime is less or equal than another specified DateTime.
Definition: datetime.h:500
constexpr bool isSameDay(const DateTime &other) const
Returns and indication whether two DateTime instances represent the same day.
Definition: datetime.h:406
constexpr int hour() const
Returns the hour component of the date represented by this instance.
Definition: datetime.h:307
static DateTime fromString(const std::string &str)
Parses the given std::string as DateTime.
Definition: datetime.h:191
constexpr int second() const
Returns the second component of the date represented by this instance.
Definition: datetime.h:323
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:177
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:158
constexpr TimeSpan timeOfDay() const
Returns the time of day as TimeSpan for this instance.
Definition: datetime.h:366
static DateTime fromChronoTimePoint(TimePoint timePoint)
Constructs a new DateTime object with the local time from the specified std::chrono::time_point.
Definition: datetime.h:232
constexpr static DateTime fromChronoTimePointGmt(TimePoint timePoint)
static DateTime gmtNow()
Returns a DateTime object that is set to the current date and time on this computer,...
Definition: datetime.h:460
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:526
constexpr bool isEternity() const
Returns whether the instance has the maximal number of ticks.
Definition: datetime.h:382
constexpr int millisecond() const
Returns the millisecond component of the date represented by this instance.
Definition: datetime.h:331
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:167
constexpr int nanosecond() const
Returns the nanosecond component of the date represented by this instance.
Definition: datetime.h:349
static DateTime fromIsoStringGmt(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition: datetime.h:202
constexpr bool operator<(const DateTime &other) const
Indicates whether a specified DateTime is less than another specified DateTime.
Definition: datetime.h:484
static int daysInMonth(int year, int month)
Returns the number of days in the specified month and year.
Definition: datetime.h:398
constexpr std::uint64_t & ticks()
Returns a mutable reference to the total ticks.
Definition: datetime.h:250
constexpr std::time_t toTimeStamp() const
Returns the UNIX timestamp for the current instance.
Definition: datetime.h:426
static constexpr DateTime eternity()
Constructs a new instance of the DateTime class with the maximal number of ticks.
Definition: datetime.h:434
constexpr int minute() const
Returns the minute component of the date represented by this instance.
Definition: datetime.h:315
int year() const
Returns the year component of the date represented by this instance.
Definition: datetime.h:266
Represents a time interval.
Definition: timespan.h:25
static constexpr std::int64_t ticksPerMinute
Definition: timespan.h:86
static constexpr std::int64_t ticksPerDay
Definition: timespan.h:88
static constexpr std::int64_t ticksPerSecond
Definition: timespan.h:85
static constexpr std::int64_t nanosecondsPerTick
Definition: timespan.h:82
static constexpr std::int64_t ticksPerHour
Definition: timespan.h:87
static constexpr std::int64_t ticksPerMicrosecond
Definition: timespan.h:83
static constexpr std::int64_t ticksPerMillisecond
Definition: timespan.h:84
#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:215
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
size_t operator()(const CppUtilities::DateTime &dateTime) const
Definition: datetime.h:573