Time in D Programming Language

import std.stdio;
import std.datetime;
import core.time;

void main()
{
    auto p = &writeln;

    // We'll start by getting the current time.
    auto now = Clock.currTime();
    p(now);

    // You can build a SysTime struct by providing the
    // year, month, day, etc. Times are always associated
    // with a TimeZone.
    auto then = SysTime(DateTime(2009, 11, 17, 20, 34, 58), 651387237.hnsecs, UTC());
    p(then);

    // You can extract the various components of the time
    // value as expected.
    p(then.year);
    p(then.month);
    p(then.day);
    p(then.hour);
    p(then.minute);
    p(then.second);
    p(then.fracSecs.total!"nsecs");
    p(then.timezone);

    // The Monday-Sunday DayOfWeek is also available.
    p(then.dayOfWeek);

    // These methods compare two times, testing if the
    // first occurs before, after, or at the same time
    // as the second, respectively.
    p(then < now);
    p(then > now);
    p(then == now);

    // The subtract operator returns a Duration representing
    // the interval between two times.
    auto diff = now - then;
    p(diff);

    // We can compute the length of the duration in
    // various units.
    p(diff.total!"hours");
    p(diff.total!"minutes");
    p(diff.total!"seconds");
    p(diff.total!"nsecs");

    // You can use the addition operator to advance a time by a given
    // duration, or with a - to move backwards by a duration.
    p(then + diff);
    p(then - diff);
}

This D program demonstrates various operations with time and duration, similar to the original Go example. Here are some key points about the translation:

  1. We use std.datetime and core.time modules for time-related functionality in D.

  2. The SysTime struct in D is similar to Go’s time.Time.

  3. D uses Clock.currTime() to get the current time, which is equivalent to Go’s time.Now().

  4. To create a specific time, we use SysTime constructor with DateTime and timezone.

  5. D’s Duration type is used for time intervals, similar to Go’s time.Duration.

  6. The total!"unit" template in D is used to get duration in specific units, replacing Go’s methods like Hours(), Minutes(), etc.

  7. D uses operators like <, >, == for time comparisons, and +, - for time arithmetic, which is similar to Go.

  8. The hnsecs unit in D represents 100-nanosecond intervals, which we use to set the fractional seconds.

This D code provides similar functionality to the Go example, allowing you to work with times, durations, and perform various time-related operations.