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:
We use
std.datetime
andcore.time
modules for time-related functionality in D.The
SysTime
struct in D is similar to Go’stime.Time
.D uses
Clock.currTime()
to get the current time, which is equivalent to Go’stime.Now()
.To create a specific time, we use
SysTime
constructor withDateTime
and timezone.D’s
Duration
type is used for time intervals, similar to Go’stime.Duration
.The
total!"unit"
template in D is used to get duration in specific units, replacing Go’s methods likeHours()
,Minutes()
, etc.D uses operators like
<
,>
,==
for time comparisons, and+
,-
for time arithmetic, which is similar to Go.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.