C++ Utilities  4.12.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 #if defined(PLATFORM_UNIX)
11 #include <time.h>
12 #endif
13 
14 using namespace std;
15 using namespace ChronoUtilities;
16 using namespace ConversionUtilities;
17 
18 const int DateTime::m_daysPerYear = 365;
19 const int DateTime::m_daysPer4Years = 1461;
20 const int DateTime::m_daysPer100Years = 36524;
21 const int DateTime::m_daysPer400Years = 146097;
22 const int DateTime::m_daysTo1601 = 584388;
23 const int DateTime::m_daysTo1899 = 693593;
24 const int DateTime::m_daysTo10000 = 3652059;
25 const int DateTime::m_daysToMonth365[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
26 const int DateTime::m_daysToMonth366[13] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
27 const int DateTime::m_daysInMonth365[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
28 const int DateTime::m_daysInMonth366[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
29 
30 template <typename num1, typename num2, typename num3> constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
31 {
32  return (val) >= (min) && (val) <= (max);
33 }
34 
35 template <typename num1, typename num2, typename num3> constexpr bool inRangeExclMax(num1 val, num2 min, num3 max)
36 {
37  return (val) >= (min) && (val) < (max);
38 }
39 
63 DateTime DateTime::fromTimeStamp(time_t timeStamp)
64 {
65  if (timeStamp) {
66  struct tm *timeinfo = localtime(&timeStamp);
67  return DateTime::fromDateAndTime(timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min,
68  timeinfo->tm_sec < 60 ? timeinfo->tm_sec : 59, 0);
69  } else {
70  return DateTime();
71  }
72 }
73 
77 DateTime DateTime::fromTimeStampGmt(time_t timeStamp)
78 {
79  return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<uint64>(timeStamp) * TimeSpan::m_ticksPerSecond);
80 }
81 
91 DateTime DateTime::fromString(const char *str)
92 {
93  int values[6] = { 0 };
94  int *const dayIndex = values + 2;
95  int *const secondsIndex = values + 5;
96  int *valueIndex = values;
97  int *const valuesEnd = values + 7;
98  double miliSecondsFact = 100.0, miliSeconds = 0.0;
99  for (const char *strIndex = str;; ++strIndex) {
100  const char c = *strIndex;
101  if (c <= '9' && c >= '0') {
102  if (valueIndex > secondsIndex) {
103  miliSeconds += (c - '0') * miliSecondsFact;
104  miliSecondsFact /= 10;
105  } else {
106  *valueIndex *= 10;
107  *valueIndex += c - '0';
108  }
109  } else if ((c == '-' || c == ':' || c == '/') || (c == '.' && (valueIndex == secondsIndex)) || (c == ' ' && (valueIndex == dayIndex))) {
110  if (++valueIndex == valuesEnd) {
111  break; // just ignore further values for now
112  }
113  } else if (c == '\0') {
114  break;
115  } else {
116  throw ConversionException(argsToString("unexpected ", c));
117  }
118  }
119  return DateTime::fromDateAndTime(values[0], values[1], *dayIndex, values[3], values[4], *secondsIndex, miliSeconds);
120 }
121 
130 std::pair<DateTime, TimeSpan> DateTime::fromIsoString(const char *str)
131 {
132  int values[9] = { 0 };
133  int *const dayIndex = values + 2;
134  int *const hourIndex = values + 3;
135  int *const secondsIndex = values + 5;
136  int *const miliSecondsIndex = values + 6;
137  int *const deltaHourIndex = values + 7;
138  int *valueIndex = values;
139  bool deltaNegative = false;
140  double miliSecondsFact = 100.0, miliSeconds = 0.0;
141  for (const char *strIndex = str;; ++strIndex) {
142  const char c = *strIndex;
143  if (c <= '9' && c >= '0') {
144  if (valueIndex == miliSecondsIndex) {
145  miliSeconds += (c - '0') * miliSecondsFact;
146  miliSecondsFact /= 10;
147  } else {
148  *valueIndex *= 10;
149  *valueIndex += c - '0';
150  }
151  } else if (c == 'T') {
152  if (++valueIndex != hourIndex) {
153  throw ConversionException("\"T\" expected before hour");
154  }
155  } else if (c == '-') {
156  if (valueIndex < dayIndex) {
157  ++valueIndex;
158  } else {
159  throw ConversionException("unexpected \"-\" after day");
160  }
161  } else if (c == '.') {
162  if (valueIndex != secondsIndex) {
163  throw ConversionException("unexpected \".\"");
164  } else {
165  ++valueIndex;
166  }
167  } else if (c == ':') {
168  if (valueIndex < hourIndex) {
169  throw ConversionException("unexpected \":\" before hour");
170  } else if (valueIndex == secondsIndex) {
171  throw ConversionException("unexpected \":\" after second");
172  } else {
173  ++valueIndex;
174  }
175  } else if ((c == '+') && (++valueIndex == deltaHourIndex)) {
176  deltaNegative = false;
177  } else if ((c == '-') && (++valueIndex == deltaHourIndex)) {
178  deltaNegative = true;
179  } else if (c == '\0') {
180  break;
181  } else {
182  throw ConversionException(argsToString("unexpected \"", c, '\"'));
183  }
184  }
185  deltaNegative && (*deltaHourIndex = -*deltaHourIndex);
186  return make_pair(DateTime::fromDateAndTime(values[0], values[1], *dayIndex, *hourIndex, values[4], *secondsIndex, miliSeconds),
187  TimeSpan::fromMinutes(*deltaHourIndex * 60 + values[8]));
188 }
189 
195 string DateTime::toString(DateTimeOutputFormat format, bool noMilliseconds) const
196 {
197  string result;
198  toString(result, format, noMilliseconds);
199  return result;
200 }
201 
207 void DateTime::toString(string &result, DateTimeOutputFormat format, bool noMilliseconds) const
208 {
209  stringstream s(stringstream::in | stringstream::out);
210  s << setfill('0');
211  if (format == DateTimeOutputFormat::DateTimeAndWeekday || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
212  s << printDayOfWeek(dayOfWeek(), format == DateTimeOutputFormat::DateTimeAndShortWeekday) << ' ';
213  if (format == DateTimeOutputFormat::DateOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
214  || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
215  s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day();
216  if (format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
217  || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
218  s << " ";
219  if (format == DateTimeOutputFormat::TimeOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
220  || format == DateTimeOutputFormat::DateTimeAndShortWeekday) {
221  s << setw(2) << hour() << ':' << setw(2) << minute() << ':' << setw(2) << second();
222  int ms = millisecond();
223  if (!noMilliseconds && ms > 0) {
224  s << '.' << setw(3) << ms;
225  }
226  }
227  result = s.str();
228 }
229 
234 string DateTime::toIsoString(TimeSpan timeZoneDelta) const
235 {
236  stringstream s(stringstream::in | stringstream::out);
237  s << setfill('0');
238  s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day() << 'T' << setw(2) << hour() << ':' << setw(2) << minute() << ':'
239  << setw(2) << second();
240  const int milli(millisecond());
241  const int micro(microsecond());
242  const int nano(nanosecond());
243  if (milli || micro || nano) {
244  s << '.' << setw(3) << milli;
245  if (micro || nano) {
246  s << setw(3) << micro;
247  if (nano) {
248  s << nano / TimeSpan::nanosecondsPerTick;
249  }
250  }
251  }
252  if (!timeZoneDelta.isNull()) {
253  s << (timeZoneDelta.isNegative() ? '-' : '+');
254  s << setw(2) << timeZoneDelta.hours() << ':' << setw(2) << timeZoneDelta.minutes();
255  }
256  return s.str();
257 }
258 
266 const char *DateTime::printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation)
267 {
268  if (abbreviation) {
269  switch (dayOfWeek) {
270  case DayOfWeek::Monday:
271  return "Mon";
272  case DayOfWeek::Tuesday:
273  return "Tue";
274  case DayOfWeek::Wednesday:
275  return "Wed";
276  case DayOfWeek::Thursday:
277  return "Thu";
278  case DayOfWeek::Friday:
279  return "Fri";
280  case DayOfWeek::Saturday:
281  return "Sat";
282  case DayOfWeek::Sunday:
283  return "Sun";
284  }
285  } else {
286  switch (dayOfWeek) {
287  case DayOfWeek::Monday:
288  return "Monday";
289  case DayOfWeek::Tuesday:
290  return "Tuesday";
291  case DayOfWeek::Wednesday:
292  return "Wednesday";
293  case DayOfWeek::Thursday:
294  return "Thursday";
295  case DayOfWeek::Friday:
296  return "Friday";
297  case DayOfWeek::Saturday:
298  return "Saturday";
299  case DayOfWeek::Sunday:
300  return "Sunday";
301  }
302  }
303  return "";
304 }
305 
306 #if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
307 
311 DateTime DateTime::exactGmtNow()
312 {
313  struct timespec t;
314  clock_gettime(CLOCK_REALTIME, &t);
315  return DateTime(
316  DateTime::unixEpochStart().totalTicks() + static_cast<uint64>(t.tv_sec) * TimeSpan::m_ticksPerSecond + static_cast<uint64>(t.tv_nsec) / 100);
317 }
318 #endif
319 
323 uint64 DateTime::dateToTicks(int year, int month, int day)
324 {
325  if (!inRangeInclMax(year, 1, 9999)) {
326  throw ConversionException("year is out of range");
327  }
328  if (!inRangeInclMax(month, 1, 12)) {
329  throw ConversionException("month is out of range");
330  }
331  const auto *const daysToMonth = reinterpret_cast<const int *>(isLeapYear(year) ? m_daysToMonth366 : m_daysToMonth365);
332  const int passedMonth = month - 1;
333  if (!inRangeInclMax(day, 1, daysToMonth[month] - daysToMonth[passedMonth])) {
334  throw ConversionException("day is out of range");
335  }
336  const auto passedYears = static_cast<unsigned int>(year - 1);
337  const auto passedDays = static_cast<unsigned int>(day - 1);
338  return (passedYears * m_daysPerYear + passedYears / 4 - passedYears / 100 + passedYears / 400
339  + static_cast<unsigned int>(daysToMonth[passedMonth]) + passedDays)
340  * TimeSpan::m_ticksPerDay;
341 }
342 
346 uint64 DateTime::timeToTicks(int hour, int minute, int second, double millisecond)
347 {
348  if (!inRangeExclMax(hour, 0, 24)) {
349  throw ConversionException("hour is out of range");
350  }
351  if (!inRangeExclMax(minute, 0, 60)) {
352  throw ConversionException("minute is out of range");
353  }
354  if (!inRangeExclMax(second, 0, 60)) {
355  throw ConversionException("second is out of range");
356  }
357  if (!inRangeExclMax(millisecond, 0.0, 1000.0)) {
358  throw ConversionException("millisecond is out of range");
359  }
360  return static_cast<uint64>(hour * TimeSpan::m_ticksPerHour) + static_cast<uint64>(minute * TimeSpan::m_ticksPerMinute)
361  + static_cast<uint64>(second * TimeSpan::m_ticksPerSecond) + static_cast<uint64>(millisecond * TimeSpan::m_ticksPerMillisecond);
362 }
363 
368 int DateTime::getDatePart(DatePart part) const
369 {
370  const int fullDays = m_ticks / TimeSpan::m_ticksPerDay;
371  const int full400YearBlocks = fullDays / m_daysPer400Years;
372  const int daysMinusFull400YearBlocks = fullDays - full400YearBlocks * m_daysPer400Years;
373  int full100YearBlocks = daysMinusFull400YearBlocks / m_daysPer100Years;
374  if (full100YearBlocks == 4) {
375  full100YearBlocks = 3;
376  }
377  const int daysMinusFull100YearBlocks = daysMinusFull400YearBlocks - full100YearBlocks * m_daysPer100Years;
378  const int full4YearBlocks = daysMinusFull100YearBlocks / m_daysPer4Years;
379  const int daysMinusFull4YearBlocks = daysMinusFull100YearBlocks - full4YearBlocks * m_daysPer4Years;
380  int full1YearBlocks = daysMinusFull4YearBlocks / m_daysPerYear;
381  if (full1YearBlocks == 4) {
382  full1YearBlocks = 3;
383  }
384  if (part == DatePart::Year) {
385  return full400YearBlocks * 400 + full100YearBlocks * 100 + full4YearBlocks * 4 + full1YearBlocks + 1;
386  }
387  const int restDays = daysMinusFull4YearBlocks - full1YearBlocks * m_daysPerYear;
388  if (part == DatePart::DayOfYear) { // day
389  return restDays + 1;
390  }
391  const int *const daysToMonth = (full1YearBlocks == 3 && (full4YearBlocks != 24 || full100YearBlocks == 3)) ? m_daysToMonth366 : m_daysToMonth365;
392  int month = 1;
393  while (restDays >= daysToMonth[month]) {
394  ++month;
395  }
396  if (part == DatePart::Month) {
397  return month;
398  } else if (part == DatePart::Day) {
399  return restDays - daysToMonth[month - 1] + 1;
400  }
401  return 0;
402 }
constexpr bool isNegative() const
Returns ture if the time interval represented by the current TimeSpan class is negative.
Definition: timespan.h:391
constexpr bool inRangeExclMax(num1 val, num2 min, num3 max)
Definition: datetime.cpp:35
Represents an instant in time, typically expressed as a date and time of day.
Definition: datetime.h:52
Contains classes providing a means for handling date and time information.
Definition: datetime.h:12
The ConversionException class is thrown by the various conversion functions of this library when a co...
Represents a time interval.
Definition: timespan.h:28
constexpr int hours() const
Returns the hours component of the time interval represented by the current TimeSpan class...
Definition: timespan.h:285
constexpr StringType argsToString(Args &&... args)
STL namespace.
std::uint64_t uint64
unsigned 64-bit integer
Definition: types.h:49
constexpr bool isNull() const
Returns ture if the time interval represented by the current TimeSpan class is null.
Definition: timespan.h:383
constexpr int minutes() const
Returns the minutes component of the time interval represented by the current TimeSpan class...
Definition: timespan.h:277
DatePart
Specifies the date part.
Definition: datetime.h:45
Contains several functions providing conversions between different data types.
DateTimeOutputFormat
Specifies the output format.
Definition: datetime.h:18
constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
Definition: datetime.cpp:30
DayOfWeek
Specifies the day of the week.
Definition: datetime.h:30