C++ Utilities  5.7.0
Useful C++ classes and routines such as argument parser, IO and conversion utilities
datetime.cpp
Go to the documentation of this file.
1 #include "./datetime.h"
2 
3 #include "../conversion/stringbuilder.h"
4 #include "../conversion/stringconversion.h"
5 
6 #include <iomanip>
7 #include <sstream>
8 #include <stdexcept>
9 
10 using namespace std;
11 
12 namespace CppUtilities {
13 
14 const int DateTime::m_daysPerYear = 365;
15 const int DateTime::m_daysPer4Years = 1461;
16 const int DateTime::m_daysPer100Years = 36524;
17 const int DateTime::m_daysPer400Years = 146097;
18 const int DateTime::m_daysTo1601 = 584388;
19 const int DateTime::m_daysTo1899 = 693593;
20 const int DateTime::m_daysTo10000 = 3652059;
21 const int DateTime::m_daysToMonth365[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
22 const int DateTime::m_daysToMonth366[13] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
23 const int DateTime::m_daysInMonth365[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
24 const int DateTime::m_daysInMonth366[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
25 
26 template <typename num1, typename num2, typename num3> constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
27 {
28  return (val) >= (min) && (val) <= (max);
29 }
30 
31 template <typename num1, typename num2, typename num3> constexpr bool inRangeExclMax(num1 val, num2 min, num3 max)
32 {
33  return (val) >= (min) && (val) < (max);
34 }
35 
59 DateTime DateTime::fromTimeStamp(time_t timeStamp)
60 {
61  if (timeStamp) {
62  struct tm *const timeinfo = localtime(&timeStamp);
63  return DateTime::fromDateAndTime(timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min,
64  timeinfo->tm_sec < 60 ? timeinfo->tm_sec : 59, 0);
65  } else {
66  return DateTime();
67  }
68 }
69 
79 DateTime DateTime::fromString(const char *str)
80 {
81  int values[6] = { 0 };
82  int *const dayIndex = values + 2;
83  int *const secondsIndex = values + 5;
84  int *valueIndex = values;
85  int *const valuesEnd = values + 7;
86  double miliSecondsFact = 100.0, miliSeconds = 0.0;
87  for (const char *strIndex = str;; ++strIndex) {
88  const char c = *strIndex;
89  if (c <= '9' && c >= '0') {
90  if (valueIndex > secondsIndex) {
91  miliSeconds += (c - '0') * miliSecondsFact;
92  miliSecondsFact /= 10;
93  } else {
94  *valueIndex *= 10;
95  *valueIndex += c - '0';
96  }
97  } else if ((c == '-' || c == ':' || c == '/') || (c == '.' && (valueIndex == secondsIndex)) || (c == ' ' && (valueIndex == dayIndex))) {
98  if (++valueIndex == valuesEnd) {
99  break; // just ignore further values for now
100  }
101  } else if (c == '\0') {
102  break;
103  } else {
104  throw ConversionException(argsToString("unexpected ", c));
105  }
106  }
107  return DateTime::fromDateAndTime(values[0], values[1], *dayIndex, values[3], values[4], *secondsIndex, miliSeconds);
108 }
109 
119 std::pair<DateTime, TimeSpan> DateTime::fromIsoString(const char *str)
120 {
121  int values[9] = { 0 };
122  int *const yearIndex = values + 0;
123  int *const monthIndex = values + 1;
124  int *const dayIndex = values + 2;
125  int *const hourIndex = values + 3;
126  int *const secondsIndex = values + 5;
127  int *const miliSecondsIndex = values + 6;
128  int *const deltaHourIndex = values + 7;
129  int *valueIndex = values;
130  bool deltaNegative = false;
131  double miliSecondsFact = 100.0, miliSeconds = 0.0;
132  for (const char *strIndex = str;; ++strIndex) {
133  const char c = *strIndex;
134  if (c <= '9' && c >= '0') {
135  if (valueIndex == miliSecondsIndex) {
136  miliSeconds += (c - '0') * miliSecondsFact;
137  miliSecondsFact /= 10;
138  } else {
139  *valueIndex *= 10;
140  *valueIndex += c - '0';
141  }
142  } else if (c == 'T') {
143  if (++valueIndex != hourIndex) {
144  throw ConversionException("\"T\" expected before hour");
145  }
146  } else if (c == '-') {
147  if (valueIndex < dayIndex) {
148  ++valueIndex;
149  } else if (++valueIndex == deltaHourIndex) {
150  deltaNegative = true;
151  } else {
152  throw ConversionException("unexpected \"-\" after day");
153  }
154  } else if (c == '.') {
155  if (valueIndex != secondsIndex) {
156  throw ConversionException("unexpected \".\"");
157  } else {
158  ++valueIndex;
159  }
160  } else if (c == ':') {
161  if (valueIndex < hourIndex) {
162  throw ConversionException("unexpected \":\" before hour");
163  } else if (valueIndex == secondsIndex) {
164  throw ConversionException("unexpected \":\" after second");
165  } else {
166  ++valueIndex;
167  }
168  } else if ((c == '+') && (++valueIndex >= secondsIndex)) {
169  valueIndex = deltaHourIndex;
170  deltaNegative = false;
171  } else if ((c == 'Z') && (++valueIndex >= secondsIndex)) {
172  valueIndex = deltaHourIndex + 2;
173  } else if (c == '\0') {
174  break;
175  } else {
176  throw ConversionException(argsToString("unexpected \"", c, '\"'));
177  }
178  }
179  auto delta(TimeSpan::fromMinutes(*deltaHourIndex * 60 + values[8]));
180  if (deltaNegative) {
181  delta = TimeSpan(-delta.totalTicks());
182  }
183  if (valueIndex < monthIndex && !*monthIndex) {
184  *monthIndex = 1;
185  }
186  if (valueIndex < dayIndex && !*dayIndex) {
187  *dayIndex = 1;
188  }
189  return make_pair(DateTime::fromDateAndTime(*yearIndex, *monthIndex, *dayIndex, *hourIndex, values[4], *secondsIndex, miliSeconds), delta);
190 }
191 
197 void DateTime::toString(string &result, DateTimeOutputFormat format, bool noMilliseconds) const
198 {
199  if (format == DateTimeOutputFormat::Iso) {
200  result = toIsoString();
201  return;
202  }
203 
204  stringstream s(stringstream::in | stringstream::out);
205  s << setfill('0');
206 
207  if (format == DateTimeOutputFormat::IsoOmittingDefaultComponents) {
208  constexpr auto dateDelimiter = '-', timeDelimiter = ':';
209  const int components[] = { year(), month(), day(), hour(), minute(), second(), millisecond(), microsecond(), nanosecond() };
210  const int *const firstTimeComponent = components + 3;
211  const int *const firstFractionalComponent = components + 6;
212  const int *const lastComponent = components + 8;
213  const int *componentsEnd = noMilliseconds ? firstFractionalComponent : lastComponent + 1;
214  for (const int *i = componentsEnd - 1; i > components; --i) {
215  if (i >= firstTimeComponent && *i == 0) {
216  componentsEnd = i;
217  } else if (i < firstTimeComponent && *i == 1) {
218  componentsEnd = i;
219  }
220  }
221  for (const int *i = components; i != componentsEnd; ++i) {
222  if (i == firstTimeComponent) {
223  s << 'T';
224  } else if (i == firstFractionalComponent) {
225  s << '.';
226  }
227  if (i == components) {
228  s << setw(4) << *i;
229  } else if (i < firstFractionalComponent) {
230  if (i < firstTimeComponent) {
231  s << dateDelimiter;
232  } else if (i > firstTimeComponent) {
233  s << timeDelimiter;
234  }
235  s << setw(2) << *i;
236  } else if (i < lastComponent) {
237  s << setw(3) << *i;
238  } else {
239  s << *i / TimeSpan::nanosecondsPerTick;
240  }
241  }
242  result = s.str();
243  return;
244  }
245 
246  if (format == DateTimeOutputFormat::DateTimeAndWeekday || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
247  s << printDayOfWeek(dayOfWeek(), format == DateTimeOutputFormat::DateTimeAndShortWeekday) << ' ';
248  if (format == DateTimeOutputFormat::DateOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
249  || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
250  s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day();
251  if (format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
252  || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
253  s << " ";
254  if (format == DateTimeOutputFormat::TimeOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
255  || format == DateTimeOutputFormat::DateTimeAndShortWeekday) {
256  s << setw(2) << hour() << ':' << setw(2) << minute() << ':' << setw(2) << second();
257  int ms = millisecond();
258  if (!noMilliseconds && ms > 0) {
259  s << '.' << setw(3) << ms;
260  }
261  }
262  result = s.str();
263 }
264 
269 string DateTime::toIsoStringWithCustomDelimiters(TimeSpan timeZoneDelta, char dateDelimiter, char timeDelimiter, char timeZoneDelimiter) const
270 {
271  stringstream s(stringstream::in | stringstream::out);
272  s << setfill('0');
273  s << setw(4) << year() << dateDelimiter << setw(2) << month() << dateDelimiter << setw(2) << day() << 'T' << setw(2) << hour() << timeDelimiter
274  << setw(2) << minute() << timeDelimiter << setw(2) << second();
275  const int milli(millisecond());
276  const int micro(microsecond());
277  const int nano(nanosecond());
278  if (milli || micro || nano) {
279  s << '.' << setw(3) << milli;
280  if (micro || nano) {
281  s << setw(3) << micro;
282  if (nano) {
283  s << nano / TimeSpan::nanosecondsPerTick;
284  }
285  }
286  }
287  if (!timeZoneDelta.isNull()) {
288  if (timeZoneDelta.isNegative()) {
289  s << '-';
290  timeZoneDelta = TimeSpan(-timeZoneDelta.totalTicks());
291  } else {
292  s << '+';
293  }
294  s << setw(2) << timeZoneDelta.hours() << timeZoneDelimiter << setw(2) << timeZoneDelta.minutes();
295  }
296  return s.str();
297 }
298 
303 string DateTime::toIsoString(TimeSpan timeZoneDelta) const
304 {
305  return toIsoStringWithCustomDelimiters(timeZoneDelta);
306 }
307 
315 const char *DateTime::printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation)
316 {
317  if (abbreviation) {
318  switch (dayOfWeek) {
319  case DayOfWeek::Monday:
320  return "Mon";
321  case DayOfWeek::Tuesday:
322  return "Tue";
323  case DayOfWeek::Wednesday:
324  return "Wed";
325  case DayOfWeek::Thursday:
326  return "Thu";
327  case DayOfWeek::Friday:
328  return "Fri";
329  case DayOfWeek::Saturday:
330  return "Sat";
331  case DayOfWeek::Sunday:
332  return "Sun";
333  }
334  } else {
335  switch (dayOfWeek) {
336  case DayOfWeek::Monday:
337  return "Monday";
338  case DayOfWeek::Tuesday:
339  return "Tuesday";
340  case DayOfWeek::Wednesday:
341  return "Wednesday";
342  case DayOfWeek::Thursday:
343  return "Thursday";
344  case DayOfWeek::Friday:
345  return "Friday";
346  case DayOfWeek::Saturday:
347  return "Saturday";
348  case DayOfWeek::Sunday:
349  return "Sunday";
350  }
351  }
352  return "";
353 }
354 
355 #if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
356 
360 DateTime DateTime::exactGmtNow()
361 {
362  struct timespec t;
363  clock_gettime(CLOCK_REALTIME, &t);
364  return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(t.tv_sec) * TimeSpan::ticksPerSecond
365  + static_cast<std::uint64_t>(t.tv_nsec) / 100);
366 }
367 #endif
368 
372 std::uint64_t DateTime::dateToTicks(int year, int month, int day)
373 {
374  if (!inRangeInclMax(year, 1, 9999)) {
375  throw ConversionException("year is out of range");
376  }
377  if (!inRangeInclMax(month, 1, 12)) {
378  throw ConversionException("month is out of range");
379  }
380  const auto *const daysToMonth = reinterpret_cast<const int *>(isLeapYear(year) ? m_daysToMonth366 : m_daysToMonth365);
381  const int passedMonth = month - 1;
382  if (!inRangeInclMax(day, 1, daysToMonth[month] - daysToMonth[passedMonth])) {
383  throw ConversionException("day is out of range");
384  }
385  const auto passedYears = static_cast<unsigned int>(year - 1);
386  const auto passedDays = static_cast<unsigned int>(day - 1);
387  return (passedYears * m_daysPerYear + passedYears / 4 - passedYears / 100 + passedYears / 400
388  + static_cast<unsigned int>(daysToMonth[passedMonth]) + passedDays)
389  * TimeSpan::ticksPerDay;
390 }
391 
395 std::uint64_t DateTime::timeToTicks(int hour, int minute, int second, double millisecond)
396 {
397  if (!inRangeExclMax(hour, 0, 24)) {
398  throw ConversionException("hour is out of range");
399  }
400  if (!inRangeExclMax(minute, 0, 60)) {
401  throw ConversionException("minute is out of range");
402  }
403  if (!inRangeExclMax(second, 0, 60)) {
404  throw ConversionException("second is out of range");
405  }
406  if (!inRangeExclMax(millisecond, 0.0, 1000.0)) {
407  throw ConversionException("millisecond is out of range");
408  }
409  return static_cast<std::uint64_t>(hour * TimeSpan::ticksPerHour) + static_cast<std::uint64_t>(minute * TimeSpan::ticksPerMinute)
410  + static_cast<std::uint64_t>(second * TimeSpan::ticksPerSecond) + static_cast<std::uint64_t>(millisecond * TimeSpan::ticksPerMillisecond);
411 }
412 
417 int DateTime::getDatePart(DatePart part) const
418 {
419  const int fullDays = m_ticks / TimeSpan::ticksPerDay;
420  const int full400YearBlocks = fullDays / m_daysPer400Years;
421  const int daysMinusFull400YearBlocks = fullDays - full400YearBlocks * m_daysPer400Years;
422  int full100YearBlocks = daysMinusFull400YearBlocks / m_daysPer100Years;
423  if (full100YearBlocks == 4) {
424  full100YearBlocks = 3;
425  }
426  const int daysMinusFull100YearBlocks = daysMinusFull400YearBlocks - full100YearBlocks * m_daysPer100Years;
427  const int full4YearBlocks = daysMinusFull100YearBlocks / m_daysPer4Years;
428  const int daysMinusFull4YearBlocks = daysMinusFull100YearBlocks - full4YearBlocks * m_daysPer4Years;
429  int full1YearBlocks = daysMinusFull4YearBlocks / m_daysPerYear;
430  if (full1YearBlocks == 4) {
431  full1YearBlocks = 3;
432  }
433  if (part == DatePart::Year) {
434  return full400YearBlocks * 400 + full100YearBlocks * 100 + full4YearBlocks * 4 + full1YearBlocks + 1;
435  }
436  const int restDays = daysMinusFull4YearBlocks - full1YearBlocks * m_daysPerYear;
437  if (part == DatePart::DayOfYear) { // day
438  return restDays + 1;
439  }
440  const int *const daysToMonth = (full1YearBlocks == 3 && (full4YearBlocks != 24 || full100YearBlocks == 3)) ? m_daysToMonth366 : m_daysToMonth365;
441  int month = 1;
442  while (restDays >= daysToMonth[month]) {
443  ++month;
444  }
445  if (part == DatePart::Month) {
446  return month;
447  } else if (part == DatePart::Day) {
448  return restDays - daysToMonth[month - 1] + 1;
449  }
450  return 0;
451 }
452 
453 } // namespace CppUtilities
CppUtilities::DateTimeOutputFormat
DateTimeOutputFormat
Specifies the output format.
Definition: datetime.h:17
CppUtilities::inRangeExclMax
constexpr bool inRangeExclMax(num1 val, num2 min, num3 max)
Definition: datetime.cpp:31
CppUtilities::inRangeInclMax
constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
Definition: datetime.cpp:26
CppUtilities::max
constexpr T max(T first, T second)
Returns the greatest of the given items.
Definition: math.h:100
CppUtilities::argsToString
StringType argsToString(Args &&... args)
Definition: stringbuilder.h:258
CppUtilities::TimeSpan::totalTicks
constexpr std::int64_t totalTicks() const
Returns the number of ticks that represent the value of the current TimeSpan class.
Definition: timespan.h:185
CppUtilities::TimeSpan::hours
constexpr int hours() const
Returns the hours component of the time interval represented by the current TimeSpan class.
Definition: timespan.h:283
CppUtilities::DatePart
DatePart
Specifies the date part.
Definition: datetime.h:46
CppUtilities::TimeSpan::minutes
constexpr int minutes() const
Returns the minutes component of the time interval represented by the current TimeSpan class.
Definition: timespan.h:275
CppUtilities
Contains all utilities provides by the c++utilities library.
Definition: argumentparser.h:17
i
constexpr int i
Definition: traitstests.cpp:106
CppUtilities::ConversionException
The ConversionException class is thrown by the various conversion functions of this library when a co...
Definition: conversionexception.h:11
CppUtilities::DayOfWeek
DayOfWeek
Specifies the day of the week.
Definition: datetime.h:31
CppUtilities::min
constexpr T min(T first, T second)
Returns the smallest of the given items.
Definition: math.h:88
CppUtilities::TimeSpan
Represents a time interval.
Definition: timespan.h:25
CppUtilities::TimeSpan::isNegative
constexpr bool isNegative() const
Returns ture if the time interval represented by the current TimeSpan class is negative.
Definition: timespan.h:402
CppUtilities::DateTime
Represents an instant in time, typically expressed as a date and time of day.
Definition: datetime.h:53
CppUtilities::TimeSpan::isNull
constexpr bool isNull() const
Returns ture if the time interval represented by the current TimeSpan class is null.
Definition: timespan.h:394
datetime.h