C++ Utilities 5.24.7
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#include <stdexcept>
9
10using namespace std;
11
12namespace CppUtilities {
13
14const int DateTime::m_daysPerYear = 365;
15const int DateTime::m_daysPer4Years = 1461;
16const int DateTime::m_daysPer100Years = 36524;
17const int DateTime::m_daysPer400Years = 146097;
18const int DateTime::m_daysTo1601 = 584388;
19const int DateTime::m_daysTo1899 = 693593;
20const int DateTime::m_daysTo10000 = 3652059;
21const int DateTime::m_daysToMonth365[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
22const int DateTime::m_daysToMonth366[13] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
23const int DateTime::m_daysInMonth365[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
24const int DateTime::m_daysInMonth366[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
25
26template <typename num1, typename num2, typename num3> constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
27{
28 return (val) >= (min) && (val) <= (max);
29}
30
31template <typename num1, typename num2, typename num3> constexpr bool inRangeExclMax(num1 val, num2 min, num3 max)
32{
33 return (val) >= (min) && (val) < (max);
34}
35
70{
71 if (timeStamp) {
72 struct tm *const timeinfo = localtime(&timeStamp);
73 return DateTime::fromDateAndTime(timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min,
74 timeinfo->tm_sec < 60 ? timeinfo->tm_sec : 59, 0);
75 } else {
76 return DateTime();
77 }
78}
79
93
105std::pair<DateTime, TimeSpan> DateTime::fromIsoString(const char *str)
106{
108 return std::make_pair(expr.value, expr.delta);
109}
110
117{
120 return;
121 }
122
123 stringstream s(stringstream::in | stringstream::out);
124 s << setfill('0');
125
127 constexpr auto dateDelimiter = '-', timeDelimiter = ':';
128 const int components[] = { year(), month(), day(), hour(), minute(), second(), millisecond(), microsecond(), nanosecond() };
129 const int *const firstTimeComponent = components + 3;
130 const int *const firstFractionalComponent = components + 6;
131 const int *const lastComponent = components + 8;
133 for (const int *i = componentsEnd - 1; i > components; --i) {
134 if (i >= firstTimeComponent && *i == 0) {
136 } else if (i < firstTimeComponent && *i == 1) {
138 }
139 }
140 for (const int *i = components; i != componentsEnd; ++i) {
141 if (i == firstTimeComponent) {
142 s << 'T';
143 } else if (i == firstFractionalComponent) {
144 s << '.';
145 }
146 if (i == components) {
147 s << setw(4) << *i;
148 } else if (i < firstFractionalComponent) {
149 if (i < firstTimeComponent) {
150 s << dateDelimiter;
151 } else if (i > firstTimeComponent) {
152 s << timeDelimiter;
153 }
154 s << setw(2) << *i;
155 } else if (i < lastComponent) {
156 s << setw(3) << *i;
157 } else {
159 }
160 }
161 result = s.str();
162 return;
163 }
164
169 s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day();
172 s << " ";
175 s << setw(2) << hour() << ':' << setw(2) << minute() << ':' << setw(2) << second();
176 int ms = millisecond();
177 if (!noMilliseconds && ms > 0) {
178 s << '.' << setw(3) << ms;
179 }
180 }
181 result = s.str();
182}
183
189{
190 stringstream s(stringstream::in | stringstream::out);
191 s << setfill('0');
192 s << setw(4) << year() << dateDelimiter << setw(2) << month() << dateDelimiter << setw(2) << day() << 'T' << setw(2) << hour() << timeDelimiter
193 << setw(2) << minute() << timeDelimiter << setw(2) << second();
194 const int milli(millisecond());
195 const int micro(microsecond());
196 const int nano(nanosecond());
197 if (milli || micro || nano) {
198 s << '.' << setw(3) << milli;
199 if (micro || nano) {
200 s << setw(3) << micro;
201 if (nano) {
203 }
204 }
205 }
206 if (!timeZoneDelta.isNull()) {
207 if (timeZoneDelta.isNegative()) {
208 s << '-';
209 timeZoneDelta = TimeSpan(-timeZoneDelta.totalTicks());
210 } else {
211 s << '+';
212 }
213 s << setw(2) << timeZoneDelta.hours() << timeZoneDelimiter << setw(2) << timeZoneDelta.minutes();
214 }
215 return s.str();
216}
217
226
234const char *DateTime::printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation)
235{
236 if (abbreviation) {
237 switch (dayOfWeek) {
239 return "Mon";
241 return "Tue";
243 return "Wed";
245 return "Thu";
247 return "Fri";
249 return "Sat";
251 return "Sun";
252 }
253 } else {
254 switch (dayOfWeek) {
256 return "Monday";
258 return "Tuesday";
260 return "Wednesday";
262 return "Thursday";
264 return "Friday";
266 return "Saturday";
268 return "Sunday";
269 }
270 }
271 return "";
272}
273
274#if defined(PLATFORM_UNIX) && !defined(PLATFORM_MAC)
279DateTime DateTime::exactGmtNow()
280{
281 struct timespec t;
283 return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast<std::uint64_t>(t.tv_sec) * TimeSpan::ticksPerSecond
284 + static_cast<std::uint64_t>(t.tv_nsec) / 100);
285}
286#endif
287
291DateTime::TickType DateTime::dateToTicks(int year, int month, int day)
292{
293 if (!inRangeInclMax(year, 1, 9999)) {
294 throw ConversionException("year is out of range");
295 }
296 if (!inRangeInclMax(month, 1, 12)) {
297 throw ConversionException("month is out of range");
298 }
299 const auto *const daysToMonth = reinterpret_cast<const int *>(isLeapYear(year) ? m_daysToMonth366 : m_daysToMonth365);
300 const int passedMonth = month - 1;
302 throw ConversionException("day is out of range");
303 }
304 const auto passedYears = static_cast<unsigned int>(year - 1);
305 const auto passedDays = static_cast<unsigned int>(day - 1);
306 return (passedYears * m_daysPerYear + passedYears / 4 - passedYears / 100 + passedYears / 400
307 + static_cast<unsigned int>(daysToMonth[passedMonth]) + passedDays)
309}
310
314DateTime::TickType DateTime::timeToTicks(int hour, int minute, int second, double millisecond)
315{
316 if (!inRangeExclMax(hour, 0, 24)) {
317 throw ConversionException("hour is out of range");
318 }
319 if (!inRangeExclMax(minute, 0, 60)) {
320 throw ConversionException("minute is out of range");
321 }
322 if (!inRangeExclMax(second, 0, 60)) {
323 throw ConversionException("second is out of range");
324 }
325 if (!inRangeExclMax(millisecond, 0.0, 1000.0)) {
326 throw ConversionException("millisecond is out of range");
327 }
328 return static_cast<std::uint64_t>(hour * TimeSpan::ticksPerHour) + static_cast<std::uint64_t>(minute * TimeSpan::ticksPerMinute)
329 + static_cast<std::uint64_t>(second * TimeSpan::ticksPerSecond) + static_cast<std::uint64_t>(millisecond * TimeSpan::ticksPerMillisecond);
330}
331
336int DateTime::getDatePart(DatePart part) const
337{
338 const auto fullDays = static_cast<int>(m_ticks / TimeSpan::ticksPerDay);
339 const auto full400YearBlocks = fullDays / m_daysPer400Years;
340 const auto daysMinusFull400YearBlocks = fullDays - full400YearBlocks * m_daysPer400Years;
341 auto full100YearBlocks = daysMinusFull400YearBlocks / m_daysPer100Years;
342 if (full100YearBlocks == 4) {
344 }
346 const auto full4YearBlocks = daysMinusFull100YearBlocks / m_daysPer4Years;
348 auto full1YearBlocks = daysMinusFull4YearBlocks / m_daysPerYear;
349 if (full1YearBlocks == 4) {
350 full1YearBlocks = 3;
351 }
352 if (part == DatePart::Year) {
354 }
355 const auto restDays = daysMinusFull4YearBlocks - full1YearBlocks * m_daysPerYear;
356 if (part == DatePart::DayOfYear) { // day
357 return restDays + 1;
358 }
359 const auto *const daysToMonth = (full1YearBlocks == 3 && (full4YearBlocks != 24 || full100YearBlocks == 3)) ? m_daysToMonth366 : m_daysToMonth365;
360 auto month = 1;
361 while (restDays >= daysToMonth[month]) {
362 ++month;
363 }
364 if (part == DatePart::Month) {
365 return month;
366 } else if (part == DatePart::Day) {
367 return restDays - daysToMonth[month - 1] + 1;
368 }
369 return 0;
370}
371
373static DateTimeParts dateTimePartsFromParsingDistance(const int *valueIndex, const int *values)
374{
375 return static_cast<DateTimeParts>((1 << (valueIndex - values + 1)) - 1);
376}
378
389{
390 auto res = DateTimeExpression();
391 int values[9] = { 0 };
392 int *const yearIndex = values + 0;
393 int *const monthIndex = values + 1;
394 int *const dayIndex = values + 2;
395 int *const hourIndex = values + 3;
396 int *const secondsIndex = values + 5;
397 int *const miliSecondsIndex = values + 6;
398 int *const deltaHourIndex = values + 7;
399 int *const valuesEnd = values + 9;
400 int *valueIndex = values;
401 unsigned int remainingDigits = 4;
402 bool deltaNegative = false;
403 double millisecondsFact = 100.0, milliseconds = 0.0;
404 for (const char *strIndex = str;; ++strIndex) {
405 const char c = *strIndex;
406 if (c <= '9' && c >= '0') {
408 milliseconds += (c - '0') * millisecondsFact;
409 millisecondsFact /= 10;
410 } else {
411 if (!remainingDigits) {
413 throw ConversionException("Max. number of digits exceeded");
414 }
415 remainingDigits = 2;
416 }
417 *valueIndex *= 10;
418 *valueIndex += c - '0';
419 remainingDigits -= 1;
420 }
421 } else if (c == 'T') {
422 if (++valueIndex != hourIndex) {
423 throw ConversionException("\"T\" expected before hour");
424 }
425 remainingDigits = 2;
426 } else if (c == '-') {
427 if (valueIndex < dayIndex) {
428 ++valueIndex;
429 } else if (++valueIndex >= secondsIndex) {
431 deltaNegative = true;
432 } else {
433 throw ConversionException("Unexpected \"-\" after day");
434 }
435 remainingDigits = 2;
436 } else if (c == '.') {
437 if (valueIndex != secondsIndex) {
438 throw ConversionException("Unexpected \".\"");
439 } else {
440 ++valueIndex;
441 }
442 } else if (c == ':') {
443 if (valueIndex < hourIndex) {
444 throw ConversionException("Unexpected \":\" before hour");
445 } else if (valueIndex == secondsIndex) {
446 throw ConversionException("Unexpected \":\" after second");
447 } else {
448 ++valueIndex;
449 }
450 remainingDigits = 2;
451 } else if ((c == '+') && (++valueIndex >= secondsIndex)) {
453 deltaNegative = false;
454 remainingDigits = 2;
455 } else if ((c == 'Z') && (++valueIndex >= secondsIndex)) {
457 remainingDigits = 2;
458 } else if (c == '\0') {
459 break;
460 } else {
461 throw ConversionException(argsToString("Unexpected \"", c, '\"'));
462 }
463 }
464 res.delta = TimeSpan::fromMinutes(*deltaHourIndex * 60 + values[8]);
465 if (deltaNegative) {
466 res.delta = TimeSpan(-res.delta.totalTicks());
467 }
468 if (valueIndex < monthIndex && !*monthIndex) {
469 *monthIndex = 1;
470 }
471 if (valueIndex < dayIndex && !*dayIndex) {
472 *dayIndex = 1;
473 }
474 res.value = DateTime::fromDateAndTime(*yearIndex, *monthIndex, *dayIndex, *hourIndex, values[4], *secondsIndex, milliseconds);
476 return res;
477}
478
489{
490 auto res = DateTimeExpression();
491 int values[7] = { 0 };
492 int *const monthIndex = values + 1;
493 int *const dayIndex = values + 2;
494 int *const secondsIndex = values + 5;
495 int *valueIndex = values;
496 int *const valuesEnd = values + 7;
497 double millisecondsFact = 100.0, milliseconds = 0.0;
498 for (const char *strIndex = str;; ++strIndex) {
499 const char c = *strIndex;
500 if (c <= '9' && c >= '0') {
501 if (valueIndex > secondsIndex) {
502 milliseconds += (c - '0') * millisecondsFact;
503 millisecondsFact /= 10;
504 } else {
505 Detail::raiseAndAdd(*valueIndex, 10, c);
506 }
507 } else if ((c == '-' || c == ':' || c == '/') || (c == '.' && (valueIndex == secondsIndex))
508 || ((c == ' ' || c == 'T') && (valueIndex == dayIndex))) {
509 if (++valueIndex == valuesEnd) {
510 break; // just ignore further values for now
511 }
512 } else if (c == '\0') {
513 break;
514 } else {
515 throw ConversionException(argsToString("Unexpected character \"", c, '\"'));
516 }
517 }
518 if (valueIndex < monthIndex && !*monthIndex) {
519 *monthIndex = 1;
520 }
521 if (valueIndex < dayIndex && !*dayIndex) {
522 *dayIndex = 1;
523 }
524 res.value = DateTime::fromDateAndTime(values[0], values[1], *dayIndex, values[3], values[4], *secondsIndex, milliseconds);
526 return res;
527}
528
534{
535 auto s = std::stringstream(std::stringstream::in | std::stringstream::out);
536 s << setfill('0');
538 s << setw(4) << value.year();
539 }
541 if (s.tellp()) {
542 s << dateDelimiter;
543 }
544 s << setw(2) << value.month();
545 }
547 if (s.tellp()) {
548 s << dateDelimiter;
549 }
550 s << setw(2) << value.day();
551 }
553 if (s.tellp()) {
554 s << 'T';
555 }
556 s << setw(2) << value.hour();
557 }
559 if (s.tellp()) {
560 s << timeDelimiter;
561 }
562 s << setw(2) << value.minute();
563 }
565 if (s.tellp()) {
566 s << timeDelimiter;
567 }
568 s << setw(2) << value.second();
569 }
571 const auto milli = value.millisecond();
572 const auto micro = value.microsecond();
573 const auto nano = value.nanosecond();
574 s << '.' << setw(3) << milli;
575 if (micro || nano) {
576 s << setw(3) << micro;
577 if (nano) {
579 }
580 }
581 }
583 auto d = delta;
584 if (d.isNegative()) {
585 s << '-';
586 d = TimeSpan(-d.totalTicks());
587 } else {
588 s << '+';
589 }
591 s << setw(2) << d.hours();
592 }
596 }
597 s << setw(2) << d.minutes();
598 }
599 }
600 return s.str();
601}
602
603} // 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:188
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:222
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:105
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:69
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:234
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
static constexpr TickType nanosecondsPerTick
Definition timespan.h:99
static constexpr TickType ticksPerMillisecond
Definition timespan.h:101
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
Contains all utilities provides 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:31
IntegralType stringToNumber(const StringType &string, BaseType base=10)
Converts the given string to an unsigned/signed number assuming string uses the specified base.
constexpr bool inRangeInclMax(num1 val, num2 min, num3 max)
Definition datetime.cpp:26
StringType argsToString(Args &&...args)
constexpr T max(T first, T second)
Returns the greatest of the given items.
Definition math.h:100
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:88
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:488
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:533
static DateTimeExpression fromIsoString(const char *str)
Parses the specified ISO date time denotation provided as C-style string.
Definition datetime.cpp:388
constexpr int i