d

How do I get the current Unix timestamp in milliseconds, in D?


How can I get the current unix timestamp (milliseconds since January 1st, 1970) as a long variable?

In other words, how would I implement this function?

long getUnixTimestampMillis() {

}

Solution

  • Updated answer!

    There are two functions in std.datetime.systime: stdTimeToUnixTime and unixTimeToStdTime, which convert between unix time (seconds since 1970-1-1) and stdTime (hecto-nanoseconds since Proleptic Gregorian Calendar epoch) See the docs for unixTimeToStdTime

    If your intent is to pass the value into a function that accepts a typical unix time (in seconds, not milliseconds), then you can the following function:

    time_t getUnixTimestamp() {
       import std.datetime;
       return Clock.currTime().stdTime().stdTimeToUnixTime();
    }
    

    However, if your goal truly is milliseconds since the unix epoch, the OP's code is correct. But here is a condensed version that doesn't rely on the unix epoch knowledge (this is how stdTimeToUnixTime works internally). The key is that SysTime(unixTimeToStdTime(0)) gives a SysTime that is set at the unix epoch. From there you can do whatever math you like.

    long getUnixTimestampMillis() {
        import std.datetime;
        return (Clock.currTime() - SysTime(unixTimeToStdTime(0)))
            .total!"msecs";
    }