DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Jesse Phillips
Jesse Phillips

Posted on

Differences of Dates in D

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));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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)));
Enter fullscreen mode Exit fullscreen mode

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)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.