DEV Community

Jesse Phillips
Jesse Phillips

Posted on

3 2

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.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more