Navigate the calendar is difficult, especially as you move back to ancient times.
Epoch, Julian, Gregorian, leap year, leap second, timezone, dates and time are complicated though assistance can be found in libraries and operating systems, but ultimately can't be ignored in many applications.
Timezone is the most common struggle. I won't be touching on best practices or how reporting my be affected. I will go over the tools D provides for comparing dates and the two types of dates.
import std.datetime;
assert(DateTime(2015, 12, 31, 23, 59, 59) + seconds(1) ==
DateTime(2016, 1, 1, 0, 0, 0));
The first type is timezone free and good at navigating dates and time.
import std.datetime;
assert(DateTime(2016, 1, 1, 0, 0, 0)
- DateTime(2015, 12, 31, 23, 59, 59)
== dur!"seconds"(1));
Performing operations on dates produces and utilizes a Duration
. While you can subtract dates, semantics for adding are not defined and the compiler will reject
// does not compile
auto fail = DateTime(2015, 12, 31, 23, 59, 59)
+ DateTime(2016, 1, 1, 0, 0, 0);
SysTime is the other object, includes timezone and operates basically the same.
import std.datetime;
assert(SysTime(DateTime(2016, 1, 1, 0, 0, 0))
- SysTime(DateTime(2015, 12, 31, 23, 59, 59))
== dur!"seconds"(1));
auto dt = SysTime(DateTime(2015, 12, 31, 23, 59, 59));
dt += dur!"seconds"(1);
assert(dt == SysTime(DateTime(2016, 1, 1, 0, 0, 0)));
dt += dur!"days"(44);
assert(dt == SysTime(DateTime(2016, 2, 14, 0, 0, 0)));
Creating a Duration
with dur
allows for manipulating the timeline. I'm not showing all operations, D provides operator overloads which allows all the normal operations with addition, subtraction, less than, greater than.
Top comments (0)