C++ Utilities  5.3.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 dayIndex = values + 2;
123  int *const hourIndex = values + 3;
124  int *const secondsIndex = values + 5;
125  int *const miliSecondsIndex = values + 6;
126  int *const deltaHourIndex = values + 7;
127  int *valueIndex = values;
128  bool deltaNegative = false;
129  double miliSecondsFact = 100.0, miliSeconds = 0.0;
130  for (const char *strIndex = str;; ++strIndex) {
131  const char c = *strIndex;
132  if (c <= '9' && c >= '0') {
133  if (valueIndex == miliSecondsIndex) {
134  miliSeconds += (c - '0') * miliSecondsFact;
135  miliSecondsFact /= 10;
136  } else {
137  *valueIndex *= 10;
138  *valueIndex += c - '0';
139  }
140  } else if (c == 'T') {
141  if (++valueIndex != hourIndex) {
142  throw ConversionException("\"T\" expected before hour");
143  }
144  } else if (c == '-') {
145  if (valueIndex < dayIndex) {
146  ++valueIndex;
147  } else if (++valueIndex == deltaHourIndex) {
148  deltaNegative = true;
149  } else {
150  throw ConversionException("unexpected \"-\" after day");
151  }
152  } else if (c == '.') {
153  if (valueIndex != secondsIndex) {
154  throw ConversionException("unexpected \".\"");
155  } else {
156  ++valueIndex;
157  }
158  } else if (c == ':') {
159  if (valueIndex < hourIndex) {
160  throw ConversionException("unexpected \":\" before hour");
161  } else if (valueIndex == secondsIndex) {
162  throw ConversionException("unexpected \":\" after second");
163  } else {
164  ++valueIndex;
165  }
166  } else if ((c == '+') && (++valueIndex >= secondsIndex)) {
167  valueIndex = deltaHourIndex;
168  deltaNegative = false;
169  } else if ((c == 'Z') && (++valueIndex >= secondsIndex)) {
170  valueIndex = deltaHourIndex + 2;
171  } else if (c == '\0') {
172  break;
173  } else {
174  throw ConversionException(argsToString("unexpected \"", c, '\"'));
175  }
176  }
177  auto delta(TimeSpan::fromMinutes(*deltaHourIndex * 60 + values[8]));
178  if (deltaNegative) {
179  delta = TimeSpan(-delta.totalTicks());
180  }
181  return make_pair(DateTime::fromDateAndTime(values[0], values[1], *dayIndex, *hourIndex, values[4], *secondsIndex, miliSeconds), delta);
182 }
183 
189 void DateTime::toString(string &result, DateTimeOutputFormat format, bool noMilliseconds) const
190 {
191  stringstream s(stringstream::in | stringstream::out);
192  s << setfill('0');
193  if (format == DateTimeOutputFormat::DateTimeAndWeekday || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
194  s << printDayOfWeek(dayOfWeek(), format == DateTimeOutputFormat::DateTimeAndShortWeekday) << ' ';
195  if (format == DateTimeOutputFormat::DateOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
196  || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
197  s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day();
198  if (format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
199  || format == DateTimeOutputFormat::DateTimeAndShortWeekday)
200  s << " ";
201  if (format == DateTimeOutputFormat::TimeOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday
202  || format == DateTimeOutputFormat::DateTimeAndShortWeekday) {
203  s << setw(2) << hour() << ':' << setw(2) << minute() << ':' << setw(2) << second();
204  int ms = millisecond();
205  if (!noMilliseconds && ms > 0) {
206  s << '.' << setw(3) << ms;
207  }
208  }
209  result = s.str();
210 }
211 
216 string DateTime::toIsoString(TimeSpan timeZoneDelta) const
217 {
218  stringstream s(stringstream::in | stringstream::out);
219  s << setfill('0');
220  s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day() << 'T' << setw(2) << hour() << ':' << setw(2) << minute() << ':'
221  << setw(2) << second();
222  const int milli(millisecond());
223  const int micro(microsecond());
224  const int nano(nanosecond());
225  if (milli || micro || nano) {
226  s << '.' << setw(3) << milli;
227  if (micro || nano) {
228  s << setw(3) << micro;
229  if (nano) {
230  s << nano / TimeSpan::nanosecondsPerTick;
231  }
232  }
233  }
234  if (!timeZoneDelta.isNull()) {
235  if (timeZoneDelta.isNegative()) {
236  s << '-';
237  timeZoneDelta = TimeSpan(-timeZoneDelta.totalTicks());
238  } else {
239  s << '+';
240  }
241  s << setw(2) << timeZoneDelta.hours() << ':' << setw(2) << timeZoneDelta.minutes();
242  }
243  return s.str();
244 }
245 
253 const char *DateTime::printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation)
254 {
255  if (abbreviation) {
256  switch (dayOfWeek) {
257  case DayOfWeek::Monday:
258  return "Mon";
259  case DayOfWeek::Tuesday:
260  return "Tue";
261  case DayOfWeek::Wednesday:
262  return "Wed";
263  case DayOfWeek::Thursday:
264  return "Thu";
265  case DayOfWeek::Friday:
266  return "Fri";
267  case DayOfWeek::Saturday:
268  return "Sat";
269  case DayOfWeek::Sunday:
270  return "Sun";
271  }
272  } else {
273  switch (dayOfWeek) {
274  case DayOfWeek::Monday:
275  return "Monday";
276  case DayOfWeek::Tuesday:
277  return "Tuesday";
278  case DayOfWeek::Wednesday:
279  return "Wednesday";
280  case DayOfWeek::Thursday:
281  return "Thursday";
282  case DayOfWeek::Friday:
283  return "Friday";
284  case DayOfWeek::Saturday:
285  return "Saturday";
286  case DayOfWeek::Sunday:
287  return "Sunday";
288  }
289  }
290  return "";
291 }
292 
293 #if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
294 
298 DateTime DateTime::exactGmtNow()
299 {
300  struct timespec t;
301  clock_gettime(CLOCK_REALTIME, &t);
302  return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(t.tv_sec) * TimeSpan::ticksPerSecond
303  + static_cast<std::uint64_t>(t.tv_nsec) / 100);
304 }
305 #endif
306 
310 std::uint64_t DateTime::dateToTicks(int year, int month, int day)
311 {
312  if (!inRangeInclMax(year, 1, 9999)) {
313  throw ConversionException("year is out of range");
314  }
315  if (!inRangeInclMax(month, 1, 12)) {
316  throw ConversionException("month is out of range");
317  }
318  const auto *const daysToMonth = reinterpret_cast<const int *>(isLeapYear(year) ? m_daysToMonth366 : m_daysToMonth365);
319  const int passedMonth = month - 1;
320  if (!inRangeInclMax(day, 1, daysToMonth[month] - daysToMonth[passedMonth])) {
321  throw ConversionException("day is out of range");
322  }
323  const auto passedYears = static_cast<unsigned int>(year - 1);
324  const auto passedDays = static_cast<unsigned int>(day - 1);
325  return (passedYears * m_daysPerYear + passedYears / 4 - passedYears / 100 + passedYears / 400
326  + static_cast<unsigned int>(daysToMonth[passedMonth]) + passedDays)
327  * TimeSpan::ticksPerDay;
328 }
329 
333 std::uint64_t DateTime::timeToTicks(int hour, int minute, int second, double millisecond)
334 {
335  if (!inRangeExclMax(hour, 0, 24)) {
336  throw ConversionException("hour is out of range");
337  }
338  if (!inRangeExclMax(minute, 0, 60)) {
339  throw ConversionException("minute is out of range");
340  }
341  if (!inRangeExclMax(second, 0, 60)) {
342  throw ConversionException("second is out of range");
343  }
344  if (!inRangeExclMax(millisecond, 0.0, 1000.0)) {
345  throw ConversionException("millisecond is out of range");
346  }
347  return static_cast<std::uint64_t>(hour * TimeSpan::ticksPerHour) + static_cast<std::uint64_t>(minute * TimeSpan::ticksPerMinute)
348  + static_cast<std::uint64_t>(second * TimeSpan::ticksPerSecond) + static_cast<std::uint64_t>(millisecond * TimeSpan::ticksPerMillisecond);
349 }
350 
355 int DateTime::getDatePart(DatePart part) const
356 {
357  const int fullDays = m_ticks / TimeSpan::ticksPerDay;
358  const int full400YearBlocks = fullDays / m_daysPer400Years;
359  const int daysMinusFull400YearBlocks = fullDays - full400YearBlocks * m_daysPer400Years;
360  int full100YearBlocks = daysMinusFull400YearBlocks / m_daysPer100Years;
361  if (full100YearBlocks == 4) {
362  full100YearBlocks = 3;
363  }
364  const int daysMinusFull100YearBlocks = daysMinusFull400YearBlocks - full100YearBlocks * m_daysPer100Years;
365  const int full4YearBlocks = daysMinusFull100YearBlocks / m_daysPer4Years;
366  const int daysMinusFull4YearBlocks = daysMinusFull100YearBlocks - full4YearBlocks * m_daysPer4Years;
367  int full1YearBlocks = daysMinusFull4YearBlocks / m_daysPerYear;
368  if (full1YearBlocks == 4) {
369  full1YearBlocks = 3;
370  }
371  if (part == DatePart::Year) {
372  return full400YearBlocks * 400 + full100YearBlocks * 100 + full4YearBlocks * 4 + full1YearBlocks + 1;
373  }
374  const int restDays = daysMinusFull4YearBlocks - full1YearBlocks * m_daysPerYear;
375  if (part == DatePart::DayOfYear) { // day
376  return restDays + 1;
377  }
378  const int *const daysToMonth = (full1YearBlocks == 3 && (full4YearBlocks != 24 || full100YearBlocks == 3)) ? m_daysToMonth366 : m_daysToMonth365;
379  int month = 1;
380  while (restDays >= daysToMonth[month]) {
381  ++month;
382  }
383  if (part == DatePart::Month) {
384  return month;
385  } else if (part == DatePart::Day) {
386  return restDays - daysToMonth[month - 1] + 1;
387  }
388  return 0;
389 }
390 
391 } // 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:44
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
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:29
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:51
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