Epoch in D Programming Language

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in D.

import std.stdio;
import std.datetime;

void main()
{
    // Use Clock.currTime to get the current time
    SysTime now = Clock.currTime();
    writeln(now);

    // Get elapsed time since the Unix epoch in seconds,
    // milliseconds or nanoseconds
    writeln(now.toUnixTime());
    writeln(now.toUnixTime() * 1000 + now.fracSecs.total!"msecs");
    writeln(now.toUnixTime() * 1_000_000_000 + now.fracSecs.total!"nsecs");

    // You can also convert integer seconds or nanoseconds
    // since the epoch into the corresponding SysTime
    writeln(SysTime.fromUnixTime(now.toUnixTime()));
    writeln(SysTime(now.toUnixTime(), now.fracSecs));
}

To run the program:

$ dmd epoch.d
$ ./epoch
2023-05-25T12:34:56.789012+00:00
1685018096
1685018096789
1685018096789012000
2023-05-25T12:34:56+00:00
2023-05-25T12:34:56.789012+00:00

In D, we use the std.datetime module to work with time. The Clock.currTime() function returns the current time as a SysTime object.

We can use toUnixTime() to get the number of seconds since the Unix epoch. For milliseconds and nanoseconds, we combine toUnixTime() with fracSecs, which represents the fractional seconds.

To convert back from Unix time to SysTime, we can use SysTime.fromUnixTime() for seconds precision, or construct a SysTime object directly for nanosecond precision.

Next, we’ll look at another time-related task: time parsing and formatting.