C++ Utilities 5.31.1
Useful C++ classes and routines such as argument parser, IO and conversion utilities
Loading...
Searching...
No Matches
datetime.cpp
Go to the documentation of this file.
1#include "./datetime.h"
2
5
6#include <iomanip>
7#include <sstream>
8
9using namespace std;
10
11namespace CppUtilities {
12
13const int DateTime::m_daysPerYear = 365;
14const int DateTime::m_daysPer4Years = 1461;
15const int DateTime::m_daysPer100Years = 36524;
16const int DateTime::m_daysPer400Years = 146097;
17const int DateTime::m_daysTo1601 = 584388;
18const int DateTime::m_daysTo1899 = 693593;
19const int DateTime::m_daysTo10000 = 3652059;
20const int DateTime::m_daysToMonth365[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
21const int DateTime::m_daysToMonth366[13] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
22const int DateTime::m_daysInMonth365[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
23const int DateTime::m_daysInMonth366[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
24
25template <typename num1, typename num2, typename num3> constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
26{
27 return (val) >= (min) && (val) <= (max);
28}
29
30template <typename num1, typename num2, typename num3> constexpr bool inRangeExclMax(num1 val, num2 min, num3 max)
31{
32 return (val) >= (min) && (val) < (max);
33}
34
52
64
69{
70 if (timeStamp) {
71 struct tm *const timeinfo = localtime(&timeStamp);
72 return DateTime::fromDateAndTime(timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min,
73 timeinfo->tm_sec < 60 ? timeinfo->tm_sec : 59, 0);
74 } else {
75 return DateTime();
76 }
77}
78
89{
91}
92
104std::pair<DateTime, TimeSpan> DateTime::fromIsoString(const char *str)
105{
106 const auto expr = DateTimeExpression::fromIsoString(str);
107 return std::make_pair(expr.value, expr.delta);
108}
109
115void DateTime::toString(string &result, DateTimeOutputFormat format, bool noMilliseconds) const
116{
117 if (format == DateTimeOutputFormat::Iso) {
118 result = toIsoString();
119 return;
120 }
121
122 stringstream s(stringstream::in | stringstream::out);
123 s << setfill('0');
124
126 constexpr auto dateDelimiter = '-', timeDelimiter = ':';
127 const int components[] = { year(), month(), day(), hour(), minute(), second(), millisecond(), microsecond(), nanosecond() };
128 const int *const firstTimeComponent = components + 3;
129 const int *const firstFractionalComponent = components + 6;
130 const int *const lastComponent = components + 8;
131 const int *componentsEnd = noMilliseconds ? firstFractionalComponent : lastComponent + 1;
132 for (const int *i = componentsEnd - 1; i > components; --i) {
133 if (i >= firstTimeComponent && *i == 0) {
134 componentsEnd = i;
135 } else if (i < firstTimeComponent && *i == 1) {
136 componentsEnd = i;
137 }
138 }
139 for (const int *i = components; i != componentsEnd; ++i) {
140 if (i == firstTimeComponent) {
141 s << 'T';
142 } else if (i == firstFractionalComponent) {
143 s << '.';
144 }
145 if (i == components) {
146 s << setw(4) << *i;
147 } else if (i < firstFractionalComponent) {
148 if (i < firstTimeComponent) {
149 s << dateDelimiter;
150 } else if (i > firstTimeComponent) {
151 s << timeDelimiter;
152 }
153 s << setw(2) << *i;
154 } else if (i < lastComponent) {
155 s << setw(3) << *i;
156 } else {
158 }
159 }
160 result = s.str();
161 return;
162 }
163
168 s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day();
171 s << " ";
174 s << setw(2) << hour() << ':' << setw(2) << minute() << ':' << setw(2) << second();
175 int ms = millisecond();
176 if (!noMilliseconds && ms > 0) {
177 s << '.' << setw(3) << ms;
178 }
179 }
180 result = s.str();
181}
182
187string DateTime::toIsoStringWithCustomDelimiters(TimeSpan timeZoneDelta, char dateDelimiter, char timeDelimiter, char timeZoneDelimiter) const
188{
189 stringstream s(stringstream::in | stringstream::out);
190 s << setfill('0');
191 s << setw(4) << year() << dateDelimiter << setw(2) << month() << dateDelimiter << setw(2) << day() << 'T' << setw(2) << hour() << timeDelimiter
192 << setw(2) << minute() << timeDelimiter << setw(2) << second();
193 const int milli(millisecond());
194 const int micro(microsecond());
195 const int nano(nanosecond());
196 if (milli || micro || nano) {
197 s << '.' << setw(3) << milli;
198 if (micro || nano) {
199 s << setw(3) << micro;
200 if (nano) {
202 }
203 }
204 }
205 if (!timeZoneDelta.isNull()) {
206 if (timeZoneDelta.isNegative()) {
207 s << '-';
208 timeZoneDelta = TimeSpan(-timeZoneDelta.totalTicks());
209 } else {
210 s << '+';
211 }
212 s << setw(2) << timeZoneDelta.hours() << timeZoneDelimiter << setw(2) << timeZoneDelta.minutes();
213 }
214 return s.str();
215}
216
221string DateTime::toIsoString(TimeSpan timeZoneDelta) const
222{
223 return toIsoStringWithCustomDelimiters(timeZoneDelta);
224}
225
233const char *DateTime::printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation)
234{
235 if (abbreviation) {
236 switch (dayOfWeek) {
238 return "Mon";
240 return "Tue";
242 return "Wed";
244 return "Thu";
246 return "Fri";
248 return "Sat";
250 return "Sun";
251 }
252 } else {
253 switch (dayOfWeek) {
255 return "Monday";
257 return "Tuesday";
259 return "Wednesday";
261 return "Thursday";
263 return "Friday";
265 return "Saturday";
267 return "Sunday";
268 }
269 }
270 return "";
271}
272
273#if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
278DateTime DateTime::exactGmtNow()
279{
280 struct timespec t;
281 clock_gettime(CLOCK_REALTIME, &t);
282 return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(t.tv_sec) * TimeSpan::ticksPerSecond
283 + static_cast<std::uint64_t>(t.tv_nsec) / 100);
284}
285#endif
286
290DateTime::TickType DateTime::dateToTicks(int year, int month, int day)
291{
292 if (!inRangeInclMax(year, 1, 9999)) {
293 throw ConversionException("year is out of range");
294 }
295 if (!inRangeInclMax(month, 1, 12)) {
296 throw ConversionException("month is out of range");
297 }
298 const auto *const daysToMonth = reinterpret_cast<const int *>(isLeapYear(year) ? m_daysToMonth366 : m_daysToMonth365);
299 const int passedMonth = month - 1;
300 if (!inRangeInclMax(day, 1, daysToMonth[month] - daysToMonth[passedMonth])) {
301 throw ConversionException("day is out of range");
302 }
303 const auto passedYears = static_cast<unsigned int>(year - 1);
304 const auto passedDays = static_cast<unsigned int>(day - 1);
305 return (passedYears * m_daysPerYear + passedYears / 4 - passedYears / 100 + passedYears / 400
306 + static_cast<unsigned int>(daysToMonth[passedMonth]) + passedDays)
308}
309
313DateTime::TickType DateTime::timeToTicks(int hour, int minute, int second, double millisecond)
314{
315 if (!inRangeExclMax(hour, 0, 24)) {
316 throw ConversionException("hour is out of range");
317 }
318 if (!inRangeExclMax(minute, 0, 60)) {
319 throw ConversionException("minute is out of range");
320 }
321 if (!inRangeExclMax(second, 0, 60)) {
322 throw ConversionException("second is out of range");
323 }
324 if (!inRangeExclMax(millisecond, 0.0, 1000.0)) {
325 throw ConversionException("millisecond is out of range");
326 }
327 return static_cast<std::uint64_t>(hour * TimeSpan::ticksPerHour) + static_cast<std::uint64_t>(minute * TimeSpan::ticksPerMinute)
328 + static_cast<std::uint64_t>(second * TimeSpan::ticksPerSecond) + static_cast<std::uint64_t>(millisecond * TimeSpan::ticksPerMillisecond);
329}
330
335int DateTime::getDatePart(DatePart part) const
336{
337 const auto fullDays = static_cast<int>(m_ticks / TimeSpan::ticksPerDay);
338 const auto full400YearBlocks = fullDays / m_daysPer400Years;
339 const auto daysMinusFull400YearBlocks = fullDays - full400YearBlocks * m_daysPer400Years;
340 auto full100YearBlocks = daysMinusFull400YearBlocks / m_daysPer100Years;
341 if (full100YearBlocks == 4) {
342 full100YearBlocks = 3;
343 }
344 const auto daysMinusFull100YearBlocks = daysMinusFull400YearBlocks - full100YearBlocks * m_daysPer100Years;
345 const auto full4YearBlocks = daysMinusFull100YearBlocks / m_daysPer4Years;
346 const auto daysMinusFull4YearBlocks = daysMinusFull100YearBlocks - full4YearBlocks * m_daysPer4Years;
347 auto full1YearBlocks = daysMinusFull4YearBlocks / m_daysPerYear;
348 if (full1YearBlocks == 4) {
349 full1YearBlocks = 3;
350 }
351 if (part == DatePart::Year) {
352 return full400YearBlocks * 400 + full100YearBlocks * 100 + full4YearBlocks * 4 + full1YearBlocks + 1;
353 }
354 const auto restDays = daysMinusFull4YearBlocks - full1YearBlocks * m_daysPerYear;
355 if (part == DatePart::DayOfYear) { // day
356 return restDays + 1;
357 }
358 const auto *const daysToMonth = (full1YearBlocks == 3 && (full4YearBlocks != 24 || full100YearBlocks == 3)) ? m_daysToMonth366 : m_daysToMonth365;
359 auto month = 1;
360 while (restDays >= daysToMonth[month]) {
361 ++month;
362 }
363 if (part == DatePart::Month) {
364 return month;
365 } else if (part == DatePart::Day) {
366 return restDays - daysToMonth[month - 1] + 1;
367 }
368 return 0;
369}
370
372static DateTimeParts dateTimePartsFromParsingDistance(const int *valueIndex, const int *values)
373{
374 return static_cast<DateTimeParts>((1 << (valueIndex - values + 1)) - 1);
375}
377
388{
389 auto res = DateTimeExpression();
390 int values[9] = { 0 };
391 int *const yearIndex = values + 0;
392 int *const monthIndex = values + 1;
393 int *const dayIndex = values + 2;
394 int *const hourIndex = values + 3;
395 int *const secondsIndex = values + 5;
396 int *const miliSecondsIndex = values + 6;
397 int *const deltaHourIndex = values + 7;
398 int *const valuesEnd = values + 9;
399 int *valueIndex = values;
400 unsigned int remainingDigits = 4;
401 bool deltaNegative = false;
402 double millisecondsFact = 100.0, milliseconds = 0.0;
403 for (const char *strIndex = str;; ++strIndex) {
404 const char c = *strIndex;
405 if (c <= '9' && c >= '0') {
406 if (valueIndex == miliSecondsIndex) {
407 milliseconds += (c - '0') * millisecondsFact;
408 millisecondsFact /= 10;
409 } else {
410 if (!remainingDigits) {
411 if (++valueIndex == miliSecondsIndex || valueIndex >= valuesEnd) {
412 throw ConversionException("Max. number of digits exceeded");
413 }
414 remainingDigits = 2;
415 }
416 *valueIndex *= 10;
417 *valueIndex += c - '0';
418 remainingDigits -= 1;
419 }
420 } else if (c == 'T') {
421 if (++valueIndex != hourIndex) {
422 throw ConversionException("\"T\" expected before hour");
423 }
424 remainingDigits = 2;
425 } else if (c == '-') {
426 if (valueIndex < dayIndex) {
427 ++valueIndex;
428 } else if (++valueIndex >= secondsIndex) {
429 valueIndex = deltaHourIndex;
430 deltaNegative = true;
431 } else {
432 throw ConversionException("Unexpected \"-\" after day");
433 }
434 remainingDigits = 2;
435 } else if (c == '.') {
436 if (valueIndex != secondsIndex) {
437 throw ConversionException("Unexpected \".\"");
438 } else {
439 ++valueIndex;
440 }
441 } else if (c == ':') {
442 if (valueIndex < hourIndex) {
443 throw ConversionException("Unexpected \":\" before hour");
444 } else if (valueIndex == secondsIndex) {
445 throw ConversionException("Unexpected \":\" after second");
446 } else {
447 ++valueIndex;
448 }
449 remainingDigits = 2;
450 } else if ((c == '+') && (++valueIndex >= secondsIndex)) {
451 valueIndex = deltaHourIndex;
452 deltaNegative = false;
453 remainingDigits = 2;
454 } else if ((c == 'Z') && (++valueIndex >= secondsIndex)) {
455 valueIndex = deltaHourIndex + 2;
456 remainingDigits = 2;
457 } else if (c == '\0') {
458 break;
459 } else {
460 throw ConversionException(argsToString("Unexpected \"", c, '\"'));
461 }
462 }
463 res.delta = TimeSpan::fromMinutes(*deltaHourIndex * 60 + values[8]);
464 if (deltaNegative) {
465 res.delta = TimeSpan(-res.delta.totalTicks());
466 }
467 if (valueIndex < monthIndex && !*monthIndex) {
468 *monthIndex = 1;
469 }
470 if (valueIndex < dayIndex && !*dayIndex) {
471 *dayIndex = 1;
472 }
473 res.value = DateTime::fromDateAndTime(*yearIndex, *monthIndex, *dayIndex, *hourIndex, values[4], *secondsIndex, milliseconds);
474 res.parts = dateTimePartsFromParsingDistance(valueIndex, values);
475 return res;
476}
477
488{
489 auto res = DateTimeExpression();
490 int values[7] = { 0 };
491 int *const monthIndex = values + 1;
492 int *const dayIndex = values + 2;
493 int *const secondsIndex = values + 5;
494 int *valueIndex = values;
495 int *const valuesEnd = values + 7;
496 double millisecondsFact = 100.0, milliseconds = 0.0;
497 for (const char *strIndex = str;; ++strIndex) {
498 const char c = *strIndex;
499 if (c <= '9' && c >= '0') {
500 if (valueIndex > secondsIndex) {
501 milliseconds += (c - '0') * millisecondsFact;
502 millisecondsFact /= 10;
503 } else {
504 Detail::raiseAndAdd(*valueIndex, 10, c);
505 }
506 } else if ((c == '-' || c == ':' || c == '/') || (c == '.' && (valueIndex == secondsIndex))
507 || ((c == ' ' || c == 'T') && (valueIndex == dayIndex))) {
508 if (++valueIndex == valuesEnd) {
509 break; // just ignore further values for now
510 }
511 } else if (c == '\0') {
512 break;
513 } else {
514 throw ConversionException(argsToString("Unexpected character \"", c, '\"'));
515 }
516 }
517 if (valueIndex < monthIndex && !*monthIndex) {
518 *monthIndex = 1;
519 }
520 if (valueIndex < dayIndex && !*dayIndex) {
521 *dayIndex = 1;
522 }
523 res.value = DateTime::fromDateAndTime(values[0], values[1], *dayIndex, values[3], values[4], *secondsIndex, milliseconds);
524 res.parts = dateTimePartsFromParsingDistance(valueIndex, values);
525 return res;
526}
527
532std::string DateTimeExpression::toIsoString(char dateDelimiter, char timeDelimiter, char timeZoneDelimiter) const
533{
534 auto s = std::stringstream(std::stringstream::in | std::stringstream::out);
535 s << setfill('0');
536 if (parts && DateTimeParts::Year) {
537 s << setw(4) << value.year();
538 }
540 if (s.tellp()) {
541 s << dateDelimiter;
542 }
543 s << setw(2) << value.month();
544 }
545 if (parts && DateTimeParts::Day) {
546 if (s.tellp()) {
547 s << dateDelimiter;
548 }
549 s << setw(2) << value.day();
550 }
551 if (parts && DateTimeParts::Hour) {
552 if (s.tellp()) {
553 s << 'T';
554 }
555 s << setw(2) << value.hour();
556 }
558 if (s.tellp()) {
559 s << timeDelimiter;
560 }
561 s << setw(2) << value.minute();
562 }
564 if (s.tellp()) {
565 s << timeDelimiter;
566 }
567 s << setw(2) << value.second();
568 }
570 const auto milli = value.millisecond();
571 const auto micro = value.microsecond();
572 const auto nano = value.nanosecond();
573 s << '.' << setw(3) << milli;
574 if (micro || nano) {
575 s << setw(3) << micro;
576 if (nano) {
578 }
579 }
580 }
582 auto d = delta;
583 if (d.isNegative()) {
584 s << '-';
585 d = TimeSpan(-d.totalTicks());
586 } else {
587 s << '+';
588 }
590 s << setw(2) << d.hours();
591 }
594 s << timeZoneDelimiter;
595 }
596 s << setw(2) << d.minutes();
597 }
598 }
599 return s.str();
600}
601
602} // namespace CppUtilities
The ConversionException class is thrown by the various conversion functions of this library when a co...
Represents an instant in time, typically expressed as a date and time of day.
Definition datetime.h:55
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:468
int day() const
Returns the day component of the date represented by this instance.
Definition datetime.h:334
constexpr DayOfWeek dayOfWeek() const
Returns the day of the week represented by this instance.
Definition datetime.h:351
std::string toIsoStringWithCustomDelimiters(TimeSpan timeZoneDelta=TimeSpan(), char dateDelimiter='-', char timeDelimiter=':', char timeZoneDelimiter=':') const
Returns the string representation of the current instance in the ISO format with custom delimiters,...
Definition datetime.cpp:187
bool isLeapYear() const
Returns an indication whether the year represented by this instance is a leap year.
Definition datetime.h:426
int month() const
Returns the month component of the date represented by this instance.
Definition datetime.h:326
constexpr DateTime()
Constructs a DateTime.
Definition datetime.h:194
std::string toIsoString(TimeSpan timeZoneDelta=TimeSpan()) const
Returns the string representation of the current instance in the ISO format, eg.
Definition datetime.cpp:221
static constexpr DateTime unixEpochStart()
Returns the DateTime object for the "1970-01-01T00:00:00Z".
Definition datetime.h:494
std::uint64_t TickType
Definition datetime.h:57
constexpr int microsecond() const
Returns the microsecond component of the date represented by this instance.
Definition datetime.h:391
static std::pair< DateTime, TimeSpan > fromIsoString(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.cpp:104
constexpr int hour() const
Returns the hour component of the date represented by this instance.
Definition datetime.h:359
static DateTime fromString(const std::string &str)
Parses the given std::string as DateTime.
Definition datetime.h:244
constexpr int second() const
Returns the second component of the date represented by this instance.
Definition datetime.h:375
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:230
constexpr TickType totalTicks() const
Returns the number of ticks which represent the value of the current instance.
Definition datetime.h:310
static DateTime fromTimeStamp(std::time_t timeStamp)
Constructs a new DateTime object with the local time from the specified UNIX timeStamp.
Definition datetime.cpp:68
constexpr int millisecond() const
Returns the millisecond component of the date represented by this instance.
Definition datetime.h:383
static const char * printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation=false)
Returns the string representation as C-style string for the given day of week.
Definition datetime.cpp:233
constexpr int nanosecond() const
Returns the nanosecond component of the date represented by this instance.
Definition datetime.h:401
constexpr int minute() const
Returns the minute component of the date represented by this instance.
Definition datetime.h:367
int year() const
Returns the year component of the date represented by this instance.
Definition datetime.h:318
Represents a time interval.
Definition timespan.h:25
constexpr bool isNull() const
Returns true if the time interval represented by the current TimeSpan class is null.
Definition timespan.h:538
static constexpr TickType nanosecondsPerTick
Definition timespan.h:99
static constexpr TickType ticksPerMillisecond
Definition timespan.h:101
constexpr int minutes() const
Returns the minutes component of the time interval represented by the current TimeSpan class.
Definition timespan.h:339
constexpr TickType totalTicks() const
Returns the number of ticks that represent the value of the current TimeSpan class.
Definition timespan.h:249
static constexpr TickType ticksPerMinute
Definition timespan.h:103
static constexpr TimeSpan fromMinutes(double minutes)
Constructs a new instance of the TimeSpan class with the specified number of minutes.
Definition timespan.h:146
static constexpr TickType ticksPerSecond
Definition timespan.h:102
static constexpr TickType ticksPerDay
Definition timespan.h:105
static constexpr TickType ticksPerHour
Definition timespan.h:104
constexpr bool isNegative() const
Returns true if the time interval represented by the current TimeSpan class is negative.
Definition timespan.h:546
constexpr int hours() const
Returns the hours component of the time interval represented by the current TimeSpan class.
Definition timespan.h:347
Contains all utilities provided by the c++utilities library.
DatePart
Specifies the date part.
Definition datetime.h:48
constexpr bool inRangeExclMax(num1 val, num2 min, num3 max)
Definition datetime.cpp:30
constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
Definition datetime.cpp:25
StringType argsToString(Args &&...args)
constexpr T max(T first, T second)
Returns the greatest of the given items.
Definition math.h:96
DateTimeParts
The DateTimeParts enum specifies which parts of a timestamp are present.
Definition datetime.h:145
DateTimeOutputFormat
Specifies the output format.
Definition datetime.h:19
constexpr T min(T first, T second)
Returns the smallest of the given items.
Definition math.h:84
DayOfWeek
Specifies the day of the week.
Definition datetime.h:33
STL namespace.
The DateTimeExpression struct holds information about a time expression (e.g.
Definition datetime.h:163
static DateTimeExpression fromString(const char *str)
Parses the given C-style string.
Definition datetime.cpp:487
std::string toIsoString(char dateDelimiter='-', char timeDelimiter=':', char timeZoneDelimiter=':') const
Returns the string representation of the current instance in the ISO format.
Definition datetime.cpp:532
static DateTimeExpression fromIsoString(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.cpp:387
constexpr int i