Programming Search⌘K

Taskintro

Get the current date and time

Also called now, current time, current date, get the time, timestamp now, utc now, local time now, read the system clock, datetime now.

Read the system clock once, keep the reading as an instant, and write it in UTC as an ISO 8601 timestamp with milliseconds. Convert to local time only to show it to a person.

Task

Get the current date and time. Read the system clock once, and keep the reading as an instant: a point on the time line with no time zone. Write it in UTC as an ISO 8601 timestamp, such as 2024-03-10T07:00:00.123Z. Convert it to the local time of a person only to show it to that person.

The real time changes on each run, so the contract tests the conversion. utc_timestamp(epoch_ns) takes one reading of the system clock in nanoseconds since 1970-01-01T00:00:00Z, without leap seconds, and returns YYYY-MM-DDTHH:MM:SS.mmmZ. The result always has three digits of milliseconds. The part under one millisecond is dropped toward the past, so a reading before 1970 goes to the earlier millisecond. The reading can be any signed 64-bit integer, which covers the years 1677 to 2262.

Each solution also has now_utc(clock). It reads the clock once and returns utc_timestamp of the reading. Its tests give a fake clock with a fixed reading and check the result. One more test uses the real clock and checks only the shape of the result and that the year is 2024 or later.

Solutions

Each solution keeps the reading as an integer and divides with a rule that goes toward the past. A division that goes toward zero puts the readings from -999999 ns to -1 ns at 1970-01-01T00:00:00.000Z, not at 1969-12-31T23:59:59.999Z.

  • Python. time.time_ns() returns an int of nanoseconds since the epoch. time.time() returns a float, and the documentation says to use time_ns() to avoid the precision loss of float. datetime.now(timezone.utc) returns an aware datetime in UTC, and datetime.now().astimezone() returns the local time with its offset. datetime.utcnow() is deprecated: it returns a naive datetime, which many methods treat as local time (see the pitfalls). The solution adds a timedelta of whole milliseconds to the epoch. The // and % of Python go toward the past.
  • JavaScript. Date.now() returns a number of milliseconds since the epoch. Browsers can reduce its precision to protect privacy. new Date().toISOString() always writes UTC with three digits of milliseconds, in 24 characters for the years 0 to 9999. The / of bigint goes toward zero, so the solution steps back one millisecond for a negative rest. Where the Temporal API is available, Temporal.Now.instant() returns an instant with nanoseconds, and Temporal.Now.zonedDateTimeISO() returns the time in the zone of the system.
  • TypeScript. The same code as JavaScript, with the types bigint and () => bigint.
  • Java. Clock.systemUTC().instant() and Instant.now() read the system clock. The documentation of Clock says to pass a Clock to each method that needs the current instant, so that a test can give Clock.fixed(...). ZonedDateTime.now() gives the time in the default zone of the JVM. Instant.toString() writes zero, three, six or nine digits of the fraction, as needed, so the solution uses a pattern with SSS. Math.floorDiv and Math.floorMod go toward the past.
  • C#. DateTimeOffset.UtcNow gives the current UTC time. DateTime.Now gives the local time with Kind set to Local, and DateTime.UtcNow gives UTC. The resolution depends on the system timer, and the documentation of DateTime.Now gives 0.5 to 15 ms. TimeProvider.System.GetUtcNow() reads the same clock, and a test gives a subclass of TimeProvider that overrides GetUtcNow. A tick of DateTimeOffset is 100 ns. The format uses the invariant culture.
  • Go. time.Now() returns the current local time: a Time with a wall clock reading, a monotonic clock reading and the local Location. UnixNano() gives the nanoseconds since the epoch, and UTC() sets the location to UTC. In the layout 2006-01-02T15:04:05.000Z07:00, .000 writes three digits of the fraction and drops the rest, and Z07:00 writes Z for UTC. time.Unix(0, ns) keeps the nanoseconds in [0, 1e9), so a negative reading goes toward the past.
  • Rust. SystemTime::now() reads the system clock. It is not monotonic. duration_since(UNIX_EPOCH) returns a Duration, or an error for a time before 1970. The standard library cannot write a calendar date, so the solution has the civil_from_days algorithm of Howard Hinnant, which converts a count of days to a year, a month and a day. A program that needs time zones uses a crate, such as chrono or jiff. div_euclid and rem_euclid go toward the past.
  • C. timespec_get(&ts, TIME_UTC) fills a struct timespec with the calendar time. On a POSIX system, clock_gettime(CLOCK_REALTIME, &ts) reads the same clock. gmtime_r converts seconds to a struct tm in UTC, and localtime_r converts them to local time. strftime writes the date, and snprintf adds the milliseconds, because struct tm has no fraction. The / of C goes toward zero, so the code has a floor_div.
  • C++. std::chrono::system_clock::now() reads the system clock, and its epoch is Unix time. floor<milliseconds> goes toward the past, and duration_cast goes toward zero. std::format("{:%FT%TZ}", t) writes a sys_time, and %T writes as many digits of the fraction as the duration has. std::chrono::zoned_time{std::chrono::current_zone(), now} gives the local time.
  • Bash. EPOCHSECONDS expands to whole seconds since the epoch, and EPOCHREALTIME to seconds with six digits of microseconds. The solution keeps only the digits of EPOCHREALTIME, so the character of the decimal point does not matter. date -u -d @SECONDS from GNU coreutils converts seconds to a UTC date. printf '%(%F %T)T' SECONDS is a builtin that converts seconds to local time with no new process.

A real reading prints a different time on each run. A program that must give the same output can print a check:

import re
from datetime import datetime, timezone

now = datetime.now(timezone.utc)
text = now.isoformat(timespec="milliseconds").replace("+00:00", "Z")
print("aware:", now.tzinfo is not None)
print("shape:", re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z", text) is not None)
print("year >= 2024:", now.year >= 2024)
Output
aware: True
shape: True
year >= 2024: True

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • epoch and billennium: 0 ns is 1970-01-01T00:00:00.000Z, and 10^18 ns is 2001-09-09T01:46:40.000Z.
  • with-milliseconds and truncate-not-round: 1710054000123456789 ns gives .123, not .124, and 999999 ns gives .000.
  • one-ns-before-epoch, one-ms-before-epoch and just-over-one-ms-before-epoch: -1 ns and -1000000 ns both give 1969-12-31T23:59:59.999Z, and -1000001 ns gives .998. A division that goes toward zero gives 1970-01-01T00:00:00.000Z for -1 ns.
  • last-ms-of-a-year: 2023-12-31T23:59:59.999999999 gives 2023-12-31T23:59:59.999Z. Rounding gives the next year.
  • leap-day, year-2000-is-leap and year-2100-is-not-leap: the year 2000 has a February 29, and the year 2100 does not.
  • after-int32-seconds: 2^31 seconds is 2038-01-19T03:14:08.000Z. A signed 32-bit time_t cannot hold it.
  • int64-max and int64-min: the ends of the signed 64-bit range of nanoseconds are 2262-04-11T23:47:16.854Z and 1677-09-21T00:12:43.145Z. JavaScript needs bigint here.

Pitfalls

  • A naive UTC time is read as local time. Python datetime.utcnow() returns a naive datetime. Methods such as timestamp() treat a naive value as local time, so the result is wrong by the UTC offset of the system. Use datetime.now(timezone.utc):

This code runs but gives a wrong answer on purpose.

import os
import time
from datetime import datetime, timezone

os.environ["TZ"] = "America/New_York"
time.tzset()

naive = datetime(2024, 1, 1, 12, 0)
aware = datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc)
print("naive:", naive.timestamp())
print("aware:", aware.timestamp())
Output
naive: 1704128400.0
aware: 1704110400.0
  • The getters of Date use the local zone. In JavaScript, getFullYear, getHours and toString use the time zone of the system, and getUTCFullYear, getUTCHours and toISOString use UTC. In New York, the epoch is in 1969:

This code runs but gives a wrong answer on purpose.

process.env.TZ = "America/New_York";
const epoch = new Date(0);
console.log(epoch.getFullYear(), epoch.getUTCFullYear());
console.log(epoch.toISOString());
Output
1969 1970
1970-01-01T00:00:00.000Z
  • Instant.toString changes its length. Java writes no fraction for a whole second, and three, six or nine digits for other values. Text of different lengths does not sort in time order, because Z sorts after .:

This code runs but gives a wrong answer on purpose.

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant a = Instant.ofEpochSecond(1_710_054_000L);
        Instant b = Instant.ofEpochSecond(1_710_054_000L, 120_000_000L);
        Instant c = Instant.ofEpochSecond(1_710_054_000L, 123_456_000L);
        System.out.println(a + " " + b + " " + c);
        System.out.println("a before b: " + a.isBefore(b));
        System.out.println("text a before text b: " + (a.toString().compareTo(b.toString()) < 0));
    }
}
Output
2024-03-10T07:00:00Z 2024-03-10T07:00:00.120Z 2024-03-10T07:00:00.123456Z
a before b: true
text a before text b: false
  • The default format of .NET comes from the culture. ToString() with no arguments uses the culture of the thread, so the same value gives different text on different systems. Give a format and CultureInfo.InvariantCulture:

This code runs but gives a wrong answer on purpose.

using System.Globalization;

var t = new DateTimeOffset(2024, 3, 10, 7, 0, 0, TimeSpan.Zero);
Console.WriteLine(t.ToString(CultureInfo.InvariantCulture));
Console.WriteLine(t.ToString(new CultureInfo("de-DE")));
Console.WriteLine(t.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'", CultureInfo.InvariantCulture));
Output
03/10/2024 07:00:00 +00:00
10.03.2024 07:00:00 +00:00
2024-03-10T07:00:00.000Z
  • == on a Go Time compares more than the instant. A Time from time.Now() has a monotonic reading, and Round(0) removes it. == compares the readings and the location, so it says false for the same instant. Use Equal:

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Now()
	u := t.Round(0)
	fmt.Println("t == u:", t == u)
	fmt.Println("t.Equal(u):", t.Equal(u))
	fmt.Println("UTC == local:", t.UTC() == t.Local())
}
Output
t == u: false
t.Equal(u): true
UTC == local: false
  • gmtime and localtime return one shared object. In C, each call can overwrite the struct tm of the call before. Use gmtime_r and localtime_r, which fill a struct tm of the caller:

This code runs but gives a wrong answer on purpose.

#include <stdio.h>
#include <time.h>

int main(void) {
    time_t a = 0;
    time_t b = 86400;
    struct tm *first = gmtime(&a);
    struct tm *second = gmtime(&b);
    printf("same object: %s\n", first == second ? "true" : "false");
    printf("day of the first: %d\n", first->tm_mday);
}
Output
same object: true
day of the first: 2
  • printf '%(...)T' -1 is not 1969. In the Bash builtin, the argument -1 means the current time and -2 means the time when the shell started. GNU date -d @-1 gives the second before the epoch:

This code runs but gives a wrong answer on purpose.

export TZ=UTC0
printf '%(%Y-%m-%dT%H:%M:%S)T\n' 0
if [[ $(printf '%(%Y)T' -1) == 1969 ]]; then echo "printf -1: 1969"; else echo "printf -1: now, not 1969"; fi
date -u -d @-1 +%Y-%m-%dT%H:%M:%S
Output
1970-01-01T00:00:00
printf -1: now, not 1969
1969-12-31T23:59:59
  • A wall clock can go back. The system clock is the time of day. A person or NTP can set it forward or back. Two readings do not give a correct duration, and a later reading can be lower. Use a monotonic clock to measure a duration (see Measure elapsed time).

Code

The build runs the native tests of each language in a pinned toolchain.

now.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-current-date-and-time/.

import time
from collections.abc import Callable
from datetime import datetime, timedelta, timezone

EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)


def utc_timestamp(epoch_ns: int) -> str:
    """Return the UTC date and time of epoch_ns as "YYYY-MM-DDTHH:MM:SS.mmmZ"."""
    # Floor division goes toward the past, so -1 ns is the last millisecond of 1969.
    ms = epoch_ns // 1_000_000
    moment = EPOCH + timedelta(milliseconds=ms)
    return f"{moment:%Y-%m-%dT%H:%M:%S}.{ms % 1000:03d}Z"


def now_utc(clock: Callable[[], int] = time.time_ns) -> str:
    """Read the clock once and return the UTC date and time of the reading."""
    # time_ns gives an int, so the nanoseconds are not rounded to a float.
    return utc_timestamp(clock())
test_now.py 54 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-current-date-and-time/.

import re
from datetime import datetime, timezone

import pytest

from now import now_utc, utc_timestamp

CASES = [
    ("epoch", 0, "1970-01-01T00:00:00.000Z"),
    ("billennium", 1000000000000000000, "2001-09-09T01:46:40.000Z"),
    ("with-milliseconds", 1710054000123456789, "2024-03-10T07:00:00.123Z"),
    ("leap-day", 1709208000000000000, "2024-02-29T12:00:00.000Z"),
    ("truncate-not-round", 999999, "1970-01-01T00:00:00.000Z"),
    ("one-ns-before-epoch", -1, "1969-12-31T23:59:59.999Z"),
    ("one-ms-before-epoch", -1000000, "1969-12-31T23:59:59.999Z"),
    ("just-over-one-ms-before-epoch", -1000001, "1969-12-31T23:59:59.998Z"),
    ("last-ms-of-a-year", 1704067199999999999, "2023-12-31T23:59:59.999Z"),
    ("year-2000-is-leap", 951782400000000000, "2000-02-29T00:00:00.000Z"),
    ("year-2100-is-not-leap", 4107542399999999999, "2100-02-28T23:59:59.999Z"),
    ("after-int32-seconds", 2147483648000000000, "2038-01-19T03:14:08.000Z"),
    ("int64-max", 9223372036854775807, "2262-04-11T23:47:16.854Z"),
    ("int64-min", -9223372036854775808, "1677-09-21T00:12:43.145Z"),
]


@pytest.mark.parametrize(("name", "epoch_ns", "want"), CASES, ids=[c[0] for c in CASES])
def test_utc_timestamp(name, epoch_ns, want):
    assert utc_timestamp(epoch_ns) == want


def test_matches_datetime_isoformat():
    moment = datetime(2024, 3, 10, 7, 0, 0, 123000, tzinfo=timezone.utc)
    want = moment.isoformat(timespec="milliseconds").replace("+00:00", "Z")
    assert utc_timestamp(1_710_054_000_123_456_789) == want


def test_now_utc_with_a_fake_clock():
    calls = []

    def clock():
        calls.append("clock")
        return 1_710_054_000_123_456_789

    assert now_utc(clock) == "2024-03-10T07:00:00.123Z"
    assert calls == ["clock"]


def test_now_utc_with_the_real_clock():
    got = now_utc()
    assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z", got)
    assert int(got[:4]) >= 2024
now.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

#ifndef NOW_HPP
#define NOW_HPP

#include <chrono>
#include <cstdint>
#include <format>
#include <string>

// Returns the UTC date and time of epoch_ns as "YYYY-MM-DDTHH:MM:SS.mmmZ".
inline std::string utc_timestamp(std::int64_t epoch_ns) {
    using namespace std::chrono;
    // floor goes toward the past. duration_cast and time_point_cast go toward zero.
    sys_time<milliseconds> ms = floor<milliseconds>(sys_time<nanoseconds>{nanoseconds{epoch_ns}});
    // %T writes as many digits of the fraction as the duration has: three for milliseconds.
    return std::format("{:%FT%TZ}", ms);
}

// Reads Clock once and returns the UTC date and time of the reading. Since C++20 the epoch of system_clock is
// 1970-01-01T00:00:00Z without leap seconds. A test can give another type with a static now().
template <typename Clock = std::chrono::system_clock>
std::string now_utc() {
    using namespace std::chrono;
    return utc_timestamp(duration_cast<nanoseconds>(Clock::now().time_since_epoch()).count());
}

#endif
test_now.cpp 74 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

#include <chrono>
#include <cstdint>
#include <cstdio>
#include <string>

#include "now.hpp"

namespace {

struct test_case {
    const char* name;
    std::int64_t epoch_ns;
    const char* want;
};

const test_case cases[] = {
    {"epoch", INT64_C(0), "1970-01-01T00:00:00.000Z"},
    {"billennium", INT64_C(1000000000000000000), "2001-09-09T01:46:40.000Z"},
    {"with-milliseconds", INT64_C(1710054000123456789), "2024-03-10T07:00:00.123Z"},
    {"leap-day", INT64_C(1709208000000000000), "2024-02-29T12:00:00.000Z"},
    {"truncate-not-round", INT64_C(999999), "1970-01-01T00:00:00.000Z"},
    {"one-ns-before-epoch", INT64_C(-1), "1969-12-31T23:59:59.999Z"},
    {"one-ms-before-epoch", INT64_C(-1000000), "1969-12-31T23:59:59.999Z"},
    {"just-over-one-ms-before-epoch", INT64_C(-1000001), "1969-12-31T23:59:59.998Z"},
    {"last-ms-of-a-year", INT64_C(1704067199999999999), "2023-12-31T23:59:59.999Z"},
    {"year-2000-is-leap", INT64_C(951782400000000000), "2000-02-29T00:00:00.000Z"},
    {"year-2100-is-not-leap", INT64_C(4107542399999999999), "2100-02-28T23:59:59.999Z"},
    {"after-int32-seconds", INT64_C(2147483648000000000), "2038-01-19T03:14:08.000Z"},
    {"int64-max", INT64_C(9223372036854775807), "2262-04-11T23:47:16.854Z"},
    {"int64-min", INT64_MIN, "1677-09-21T00:12:43.145Z"},
};

int calls = 0;

// A clock with one fixed reading that counts its calls.
struct fake_clock {
    static std::chrono::sys_time<std::chrono::nanoseconds> now() {
        ++calls;
        return std::chrono::sys_time<std::chrono::nanoseconds>{std::chrono::nanoseconds{INT64_C(1710054000123456789)}};
    }
};

}  // namespace

int main() {
    int failed = 0;
    for (const auto& c : cases) {
        std::string got = utc_timestamp(c.epoch_ns);
        if (got != c.want) {
            std::printf("FAIL %s: got %s, want %s\n", c.name, got.c_str(), c.want);
            failed++;
        }
    }

    std::string fake = now_utc<fake_clock>();
    if (fake != "2024-03-10T07:00:00.123Z" || calls != 1) {
        std::printf("FAIL fake clock: got %s, %d calls\n", fake.c_str(), calls);
        failed++;
    }

    std::string real = now_utc();
    if (real.size() != 24 || real[10] != 'T' || real[19] != '.' || real[23] != 'Z' || std::stoi(real.substr(0, 4)) < 2024) {
        std::printf("FAIL real clock: got %s\n", real.c_str());
        failed++;
    }

    if (failed == 0) {
        std::printf("ok\n");
    }
    return failed != 0;
}
Now.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;

/** Reads the current date and time and writes it in UTC. */
public final class Now {
    private Now() {}

    // Instant.toString drops a zero fraction, so the pattern fixes three digits of milliseconds.
    private static final DateTimeFormatter UTC_MILLIS =
            DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT).withZone(ZoneOffset.UTC);

    /** Returns the UTC date and time of epochNs as "YYYY-MM-DDTHH:MM:SS.mmmZ". */
    public static String utcTimestamp(long epochNs) {
        // floorDiv and floorMod go toward the past, so the nanoseconds of an Instant are never negative.
        Instant instant = Instant.ofEpochSecond(Math.floorDiv(epochNs, 1_000_000_000L), Math.floorMod(epochNs, 1_000_000_000L));
        return UTC_MILLIS.format(instant.truncatedTo(ChronoUnit.MILLIS));
    }

    /** Reads the clock once and returns the UTC date and time of the reading. */
    public static String nowUtc(Clock clock) {
        Instant now = clock.instant();
        return utcTimestamp(Math.addExact(Math.multiplyExact(now.getEpochSecond(), 1_000_000_000L), now.getNano()));
    }

    /** Reads the system clock, which is the best available clock of the system in UTC. */
    public static String nowUtc() {
        return nowUtc(Clock.systemUTC());
    }
}
NowTest.java 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class NowTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("epoch", 0L, "1970-01-01T00:00:00.000Z"),
                Arguments.of("billennium", 1000000000000000000L, "2001-09-09T01:46:40.000Z"),
                Arguments.of("with-milliseconds", 1710054000123456789L, "2024-03-10T07:00:00.123Z"),
                Arguments.of("leap-day", 1709208000000000000L, "2024-02-29T12:00:00.000Z"),
                Arguments.of("truncate-not-round", 999999L, "1970-01-01T00:00:00.000Z"),
                Arguments.of("one-ns-before-epoch", -1L, "1969-12-31T23:59:59.999Z"),
                Arguments.of("one-ms-before-epoch", -1000000L, "1969-12-31T23:59:59.999Z"),
                Arguments.of("just-over-one-ms-before-epoch", -1000001L, "1969-12-31T23:59:59.998Z"),
                Arguments.of("last-ms-of-a-year", 1704067199999999999L, "2023-12-31T23:59:59.999Z"),
                Arguments.of("year-2000-is-leap", 951782400000000000L, "2000-02-29T00:00:00.000Z"),
                Arguments.of("year-2100-is-not-leap", 4107542399999999999L, "2100-02-28T23:59:59.999Z"),
                Arguments.of("after-int32-seconds", 2147483648000000000L, "2038-01-19T03:14:08.000Z"),
                Arguments.of("int64-max", 9223372036854775807L, "2262-04-11T23:47:16.854Z"),
                Arguments.of("int64-min", Long.MIN_VALUE, "1677-09-21T00:12:43.145Z")
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void utcTimestamp(String name, long epochNs, String want) {
        assertEquals(want, Now.utcTimestamp(epochNs));
    }

    @Test
    void instantToStringDropsAZeroFraction() {
        assertEquals("1970-01-01T00:00:00Z", Instant.EPOCH.toString());
        assertEquals("1970-01-01T00:00:00.000Z", Now.utcTimestamp(0L));
    }

    @Test
    void nowUtcWithAFixedClock() {
        Clock clock = Clock.fixed(Instant.ofEpochSecond(1_710_054_000L, 123_456_789L), ZoneId.of("America/New_York"));
        // The zone of the clock does not change the instant.
        assertEquals("2024-03-10T07:00:00.123Z", Now.nowUtc(clock));
    }

    @Test
    void nowUtcWithTheRealClock() {
        String got = Now.nowUtc();
        assertTrue(got.matches("\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z"), got);
        assertTrue(Integer.parseInt(got.substring(0, 4)) >= 2024, got);
        assertEquals(ZoneOffset.UTC, Clock.systemUTC().getZone());
    }
}
now.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

#define _POSIX_C_SOURCE 200809L

#include "now.h"

#include <stdio.h>
#include <time.h>

int64_t system_ns(void *ctx) {
    (void)ctx;
    struct timespec ts;
    // TIME_UTC is the calendar time of the system clock. A person or NTP can set it.
    timespec_get(&ts, TIME_UTC);
    return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}

// floor_div divides and rounds toward the past. The / of C rounds toward zero.
static int64_t floor_div(int64_t a, int64_t b) {
    int64_t q = a / b;
    return (a % b < 0) ? q - 1 : q;
}

int utc_timestamp(int64_t epoch_ns, char *buf, size_t size) {
    int64_t ms = floor_div(epoch_ns, 1000000);
    int64_t secs = floor_div(ms, 1000);
    int millis = (int)(ms - secs * 1000);
    time_t t = (time_t)secs;
    struct tm tm;
    // gmtime_r fills the caller's struct. gmtime returns a static one that the next call overwrites.
    if (gmtime_r(&t, &tm) == NULL) {
        return -1;
    }
    char date[20];
    strftime(date, sizeof date, "%Y-%m-%dT%H:%M:%S", &tm);
    return snprintf(buf, size, "%s.%03dZ", date, millis);
}

int now_utc(now_clock *clock, void *clock_ctx, char *buf, size_t size) {
    return utc_timestamp(clock(clock_ctx), buf, size);
}
now.h 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

#ifndef NOW_H
#define NOW_H

#include <stddef.h>
#include <stdint.h>

// A clock returns nanoseconds since 1970-01-01T00:00:00Z. ctx is passed through.
typedef int64_t now_clock(void *ctx);

// The real clock: timespec_get with TIME_UTC, in nanoseconds. ctx is not used.
int64_t system_ns(void *ctx);

// Writes the UTC date and time of epoch_ns as "YYYY-MM-DDTHH:MM:SS.mmmZ" to buf.
// Returns the length of the text, as snprintf does, or -1 when the date has no
// broken-down form. 25 bytes are always enough.
int utc_timestamp(int64_t epoch_ns, char *buf, size_t size);

// Reads clock once and writes the UTC date and time of the reading to buf.
int now_utc(now_clock *clock, void *clock_ctx, char *buf, size_t size);

#endif
test_now.c 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

#include "now.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    int64_t epoch_ns;
    const char *want;
};

static const struct test_case cases[] = {
    {"epoch", INT64_C(0), "1970-01-01T00:00:00.000Z"},
    {"billennium", INT64_C(1000000000000000000), "2001-09-09T01:46:40.000Z"},
    {"with-milliseconds", INT64_C(1710054000123456789), "2024-03-10T07:00:00.123Z"},
    {"leap-day", INT64_C(1709208000000000000), "2024-02-29T12:00:00.000Z"},
    {"truncate-not-round", INT64_C(999999), "1970-01-01T00:00:00.000Z"},
    {"one-ns-before-epoch", INT64_C(-1), "1969-12-31T23:59:59.999Z"},
    {"one-ms-before-epoch", INT64_C(-1000000), "1969-12-31T23:59:59.999Z"},
    {"just-over-one-ms-before-epoch", INT64_C(-1000001), "1969-12-31T23:59:59.998Z"},
    {"last-ms-of-a-year", INT64_C(1704067199999999999), "2023-12-31T23:59:59.999Z"},
    {"year-2000-is-leap", INT64_C(951782400000000000), "2000-02-29T00:00:00.000Z"},
    {"year-2100-is-not-leap", INT64_C(4107542399999999999), "2100-02-28T23:59:59.999Z"},
    {"after-int32-seconds", INT64_C(2147483648000000000), "2038-01-19T03:14:08.000Z"},
    {"int64-max", INT64_C(9223372036854775807), "2262-04-11T23:47:16.854Z"},
    {"int64-min", INT64_MIN, "1677-09-21T00:12:43.145Z"},
};

// The fake clock returns one fixed reading and counts the calls.
static int64_t fake_now(void *ctx) {
    int *calls = ctx;
    ++*calls;
    return INT64_C(1710054000123456789);
}

int main(void) {
    int failed = 0;
    char buf[32];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        int n = utc_timestamp(cases[i].epoch_ns, buf, sizeof buf);
        if (n != 24 || strcmp(buf, cases[i].want) != 0) {
            printf("FAIL %s: got %s (%d), want %s\n", cases[i].name, buf, n, cases[i].want);
            failed++;
        }
    }

    int calls = 0;
    now_utc(fake_now, &calls, buf, sizeof buf);
    if (strcmp(buf, "2024-03-10T07:00:00.123Z") != 0 || calls != 1) {
        printf("FAIL fake clock: got %s, %d calls\n", buf, calls);
        failed++;
    }

    int n = now_utc(system_ns, NULL, buf, sizeof buf);
    if (n != 24 || buf[10] != 'T' || buf[19] != '.' || buf[23] != 'Z' || atoi(buf) < 2024) {
        printf("FAIL real clock: got %s\n", buf);
        failed++;
    }

    if (failed == 0) {
        printf("ok\n");
    }
    return failed != 0;
}
Now.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

using System.Globalization;

/// <summary>Reads the current date and time and writes it in UTC.</summary>
public static class Now
{
    /// <summary>Returns the UTC date and time of epochNs as "YYYY-MM-DDTHH:MM:SS.mmmZ".</summary>
    public static string UtcTimestamp(long epochNs)
    {
        // The / of C# rounds toward zero. Step back one millisecond for a negative reading with a rest.
        long ms = epochNs / 1_000_000;
        if (epochNs % 1_000_000 < 0)
        {
            ms--;
        }
        // The invariant culture keeps the digits and the separators fixed. fff truncates; it does not round.
        return DateTimeOffset.FromUnixTimeMilliseconds(ms)
            .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'", CultureInfo.InvariantCulture);
    }

    /// <summary>Reads the clock of time once and returns the UTC date and time of the reading.</summary>
    /// <remarks>TimeProvider.System reads DateTimeOffset.UtcNow. A test can give a fake TimeProvider.</remarks>
    public static string NowUtc(TimeProvider? time = null)
    {
        time ??= TimeProvider.System;
        DateTimeOffset now = time.GetUtcNow();
        // A tick is 100 nanoseconds.
        long ns = checked((now.UtcTicks - DateTimeOffset.UnixEpoch.UtcTicks) * 100);
        return UtcTimestamp(ns);
    }
}
NowTests.cs 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

using System.Globalization;
using System.Text.RegularExpressions;
using Xunit;

public sealed class NowTests
{
    public static TheoryData<string, long, string> Cases => new()
    {
        { "epoch", 0L, "1970-01-01T00:00:00.000Z" },
        { "billennium", 1000000000000000000L, "2001-09-09T01:46:40.000Z" },
        { "with-milliseconds", 1710054000123456789L, "2024-03-10T07:00:00.123Z" },
        { "leap-day", 1709208000000000000L, "2024-02-29T12:00:00.000Z" },
        { "truncate-not-round", 999999L, "1970-01-01T00:00:00.000Z" },
        { "one-ns-before-epoch", -1L, "1969-12-31T23:59:59.999Z" },
        { "one-ms-before-epoch", -1000000L, "1969-12-31T23:59:59.999Z" },
        { "just-over-one-ms-before-epoch", -1000001L, "1969-12-31T23:59:59.998Z" },
        { "last-ms-of-a-year", 1704067199999999999L, "2023-12-31T23:59:59.999Z" },
        { "year-2000-is-leap", 951782400000000000L, "2000-02-29T00:00:00.000Z" },
        { "year-2100-is-not-leap", 4107542399999999999L, "2100-02-28T23:59:59.999Z" },
        { "after-int32-seconds", 2147483648000000000L, "2038-01-19T03:14:08.000Z" },
        { "int64-max", 9223372036854775807L, "2262-04-11T23:47:16.854Z" },
        { "int64-min", long.MinValue, "1677-09-21T00:12:43.145Z" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void UtcTimestamp(string name, long epochNs, string want)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Equal(want, Now.UtcTimestamp(epochNs));
    }

    private sealed class FixedTime(DateTimeOffset now) : TimeProvider
    {
        public int Calls { get; private set; }

        public override DateTimeOffset GetUtcNow()
        {
            Calls++;
            return now;
        }
    }

    [Fact]
    public void NowUtcWithAFakeClock()
    {
        // The offset of the value does not change the instant.
        var time = new FixedTime(new DateTimeOffset(2024, 3, 10, 3, 0, 0, 123, TimeSpan.FromHours(-4)).AddTicks(4567));
        Assert.Equal("2024-03-10T07:00:00.123Z", Now.NowUtc(time));
        Assert.Equal(1, time.Calls);
    }

    [Fact]
    public void NowUtcWithTheRealClock()
    {
        string got = Now.NowUtc();
        Assert.Matches(new Regex(@"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$"), got);
        Assert.True(int.Parse(got[..4], CultureInfo.InvariantCulture) >= 2024, got);
    }
}
now.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

/**
 * Returns the UTC date and time of epochNs as "YYYY-MM-DDTHH:MM:SS.mmmZ".
 * @param {bigint} epochNs nanoseconds since 1970-01-01T00:00:00Z
 * @returns {string}
 */
export function utcTimestamp(epochNs) {
  // bigint division truncates toward zero. Step back one millisecond for a
  // negative reading with a rest, so the result goes toward the past.
  let ms = epochNs / 1_000_000n;
  if (epochNs % 1_000_000n < 0n) ms -= 1n;
  // A Date holds whole milliseconds, and toISOString always writes three digits.
  return new Date(Number(ms)).toISOString();
}

/** The real clock: Date.now() in nanoseconds. It has whole milliseconds only. */
export function systemNs() {
  return BigInt(Date.now()) * 1_000_000n;
}

/**
 * Reads the clock once and returns the UTC date and time of the reading.
 * @param {() => bigint} clock
 * @returns {string}
 */
export function nowUtc(clock = systemNs) {
  return utcTimestamp(clock());
}
now.test.js 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { nowUtc, utcTimestamp } from "./now.js";

const cases = [
  ["epoch", 0n, "1970-01-01T00:00:00.000Z"],
  ["billennium", 1000000000000000000n, "2001-09-09T01:46:40.000Z"],
  ["with-milliseconds", 1710054000123456789n, "2024-03-10T07:00:00.123Z"],
  ["leap-day", 1709208000000000000n, "2024-02-29T12:00:00.000Z"],
  ["truncate-not-round", 999999n, "1970-01-01T00:00:00.000Z"],
  ["one-ns-before-epoch", -1n, "1969-12-31T23:59:59.999Z"],
  ["one-ms-before-epoch", -1000000n, "1969-12-31T23:59:59.999Z"],
  ["just-over-one-ms-before-epoch", -1000001n, "1969-12-31T23:59:59.998Z"],
  ["last-ms-of-a-year", 1704067199999999999n, "2023-12-31T23:59:59.999Z"],
  ["year-2000-is-leap", 951782400000000000n, "2000-02-29T00:00:00.000Z"],
  ["year-2100-is-not-leap", 4107542399999999999n, "2100-02-28T23:59:59.999Z"],
  ["after-int32-seconds", 2147483648000000000n, "2038-01-19T03:14:08.000Z"],
  ["int64-max", 9223372036854775807n, "2262-04-11T23:47:16.854Z"],
  ["int64-min", -9223372036854775808n, "1677-09-21T00:12:43.145Z"],
];

for (const [name, epochNs, want] of cases) {
  test(name, () => {
    assert.equal(utcTimestamp(epochNs), want);
  });
}

test("bigint division alone truncates toward zero", () => {
  assert.equal(-1n / 1_000_000n, 0n);
  assert.equal(utcTimestamp(-1n), "1969-12-31T23:59:59.999Z");
});

test("nowUtc with a fake clock", () => {
  const calls = [];
  const clock = () => {
    calls.push("clock");
    return 1_710_054_000_123_456_789n;
  };
  assert.equal(nowUtc(clock), "2024-03-10T07:00:00.123Z");
  assert.deepEqual(calls, ["clock"]);
});

test("nowUtc with the real clock", () => {
  const got = nowUtc();
  assert.match(got, /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/);
  assert.ok(Number(got.slice(0, 4)) >= 2024);
});
now.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

/**
 * Returns the UTC date and time of epochNs as "YYYY-MM-DDTHH:MM:SS.mmmZ".
 * @param epochNs nanoseconds since 1970-01-01T00:00:00Z
 */
export function utcTimestamp(epochNs: bigint): string {
  // bigint division truncates toward zero. Step back one millisecond for a
  // negative reading with a rest, so the result goes toward the past.
  let ms = epochNs / 1_000_000n;
  if (epochNs % 1_000_000n < 0n) ms -= 1n;
  // A Date holds whole milliseconds, and toISOString always writes three digits.
  return new Date(Number(ms)).toISOString();
}

/** The real clock: Date.now() in nanoseconds. It has whole milliseconds only. */
export function systemNs(): bigint {
  return BigInt(Date.now()) * 1_000_000n;
}

/**
 * Reads the clock once and returns the UTC date and time of the reading.
 */
export function nowUtc(clock: () => bigint = systemNs): string {
  return utcTimestamp(clock());
}
now.test.ts 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { nowUtc, utcTimestamp } from "./now.ts";

const cases: [string, bigint, string][] = [
  ["epoch", 0n, "1970-01-01T00:00:00.000Z"],
  ["billennium", 1000000000000000000n, "2001-09-09T01:46:40.000Z"],
  ["with-milliseconds", 1710054000123456789n, "2024-03-10T07:00:00.123Z"],
  ["leap-day", 1709208000000000000n, "2024-02-29T12:00:00.000Z"],
  ["truncate-not-round", 999999n, "1970-01-01T00:00:00.000Z"],
  ["one-ns-before-epoch", -1n, "1969-12-31T23:59:59.999Z"],
  ["one-ms-before-epoch", -1000000n, "1969-12-31T23:59:59.999Z"],
  ["just-over-one-ms-before-epoch", -1000001n, "1969-12-31T23:59:59.998Z"],
  ["last-ms-of-a-year", 1704067199999999999n, "2023-12-31T23:59:59.999Z"],
  ["year-2000-is-leap", 951782400000000000n, "2000-02-29T00:00:00.000Z"],
  ["year-2100-is-not-leap", 4107542399999999999n, "2100-02-28T23:59:59.999Z"],
  ["after-int32-seconds", 2147483648000000000n, "2038-01-19T03:14:08.000Z"],
  ["int64-max", 9223372036854775807n, "2262-04-11T23:47:16.854Z"],
  ["int64-min", -9223372036854775808n, "1677-09-21T00:12:43.145Z"],
];

for (const [name, epochNs, want] of cases) {
  test(name, () => {
    assert.equal(utcTimestamp(epochNs), want);
  });
}

test("bigint division alone truncates toward zero", () => {
  assert.equal(-1n / 1_000_000n, 0n);
  assert.equal(utcTimestamp(-1n), "1969-12-31T23:59:59.999Z");
});

test("nowUtc with a fake clock", () => {
  const calls: string[] = [];
  const clock = () => {
    calls.push("clock");
    return 1_710_054_000_123_456_789n;
  };
  assert.equal(nowUtc(clock), "2024-03-10T07:00:00.123Z");
  assert.deepEqual(calls, ["clock"]);
});

test("nowUtc with the real clock", () => {
  const got = nowUtc();
  assert.match(got, /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/);
  assert.ok(Number(got.slice(0, 4)) >= 2024);
});
now.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

// Package now reads the current date and time and writes it in UTC.
package now

import "time"

// utcMillis is the layout of the result. Go writes the fraction .000 with
// three digits and drops the rest; it does not round.
const utcMillis = "2006-01-02T15:04:05.000Z07:00"

// UTCTimestamp returns the UTC date and time of epochNs as
// "YYYY-MM-DDTHH:MM:SS.mmmZ".
func UTCTimestamp(epochNs int64) string {
	// time.Unix keeps the nanoseconds in [0, 1e9), so a negative reading goes
	// toward the past. UTC makes the layout write Z for the offset.
	return time.Unix(0, epochNs).UTC().Format(utcMillis)
}

// NowUTC reads the clock once and returns the UTC date and time of the
// reading. time.Now is the real clock.
func NowUTC(clock func() time.Time) string {
	return UTCTimestamp(clock().UnixNano())
}
now_test.go 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

package now

import (
	"math"
	"regexp"
	"strconv"
	"testing"
	"time"
)

var cases = []struct {
	name    string
	epochNs int64
	want    string
}{
	{"epoch", 0, "1970-01-01T00:00:00.000Z"},
	{"billennium", 1000000000000000000, "2001-09-09T01:46:40.000Z"},
	{"with-milliseconds", 1710054000123456789, "2024-03-10T07:00:00.123Z"},
	{"leap-day", 1709208000000000000, "2024-02-29T12:00:00.000Z"},
	{"truncate-not-round", 999999, "1970-01-01T00:00:00.000Z"},
	{"one-ns-before-epoch", -1, "1969-12-31T23:59:59.999Z"},
	{"one-ms-before-epoch", -1000000, "1969-12-31T23:59:59.999Z"},
	{"just-over-one-ms-before-epoch", -1000001, "1969-12-31T23:59:59.998Z"},
	{"last-ms-of-a-year", 1704067199999999999, "2023-12-31T23:59:59.999Z"},
	{"year-2000-is-leap", 951782400000000000, "2000-02-29T00:00:00.000Z"},
	{"year-2100-is-not-leap", 4107542399999999999, "2100-02-28T23:59:59.999Z"},
	{"after-int32-seconds", 2147483648000000000, "2038-01-19T03:14:08.000Z"},
	{"int64-max", 9223372036854775807, "2262-04-11T23:47:16.854Z"},
	{"int64-min", math.MinInt64, "1677-09-21T00:12:43.145Z"},
}

func TestUTCTimestamp(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := UTCTimestamp(c.epochNs); got != c.want {
				t.Errorf("UTCTimestamp(%d) = %q, want %q", c.epochNs, got, c.want)
			}
		})
	}
}

func TestNowUTCWithAFakeClock(t *testing.T) {
	calls := 0
	ny, err := time.LoadLocation("America/New_York")
	if err != nil {
		t.Skip("no tz database:", err)
	}
	clock := func() time.Time {
		calls++
		// The location of the time does not change the instant.
		return time.Unix(1710054000, 123456789).In(ny)
	}
	if got, want := NowUTC(clock), "2024-03-10T07:00:00.123Z"; got != want {
		t.Errorf("NowUTC = %q, want %q", got, want)
	}
	if calls != 1 {
		t.Errorf("the clock was read %d times, want 1", calls)
	}
}

func TestNowUTCWithTheRealClock(t *testing.T) {
	got := NowUTC(time.Now)
	if !regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$`).MatchString(got) {
		t.Fatalf("NowUTC(time.Now) = %q", got)
	}
	if year, _ := strconv.Atoi(got[:4]); year < 2024 {
		t.Errorf("year %d < 2024", year)
	}
}

func TestInt64Limits(t *testing.T) {
	if UTCTimestamp(math.MaxInt64)[:4] != "2262" {
		t.Error("math.MaxInt64 is not in 2262")
	}
}
now.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

//! Reads the current date and time and writes it in UTC.

use std::time::{SystemTime, UNIX_EPOCH};

/// Returns the year, month and day of a count of days since 1970-01-01, in
/// the proleptic Gregorian calendar. This is the `civil_from_days` algorithm
/// of Howard Hinnant: it counts in eras of 400 years that start on March 1.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097); // [0, 146096]
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11], March is 0
    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
    let year = yoe + era * 400 + i64::from(month <= 2);
    (year, month, day)
}

/// Returns the UTC date and time of `epoch_ns` as "YYYY-MM-DDTHH:MM:SS.mmmZ".
pub fn utc_timestamp(epoch_ns: i64) -> String {
    // div_euclid goes toward the past for a positive divisor. The / of Rust goes toward zero.
    let ms = epoch_ns.div_euclid(1_000_000);
    let secs = ms.div_euclid(1_000);
    let days = secs.div_euclid(86_400);
    let sod = secs.rem_euclid(86_400);
    let (year, month, day) = civil_from_days(days);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
        sod / 3_600,
        sod / 60 % 60,
        sod % 60,
        ms.rem_euclid(1_000)
    )
}

/// The real clock: `SystemTime::now()` in nanoseconds since the Unix epoch.
/// `duration_since` returns an error for a time before 1970.
pub fn system_ns() -> i64 {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(d) => i64::try_from(d.as_nanos()).unwrap_or(i64::MAX),
        Err(e) => i64::try_from(e.duration().as_nanos()).map_or(i64::MIN, |n| -n),
    }
}

/// Reads the clock once and returns the UTC date and time of the reading.
pub fn now_utc(mut clock: impl FnMut() -> i64) -> String {
    utc_timestamp(clock())
}
tests/now_test.rs 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-current-date-and-time/.

use algo_get_the_current_date_and_time::{now_utc, system_ns, utc_timestamp};

const CASES: &[(&str, i64, &str)] = &[
    ("epoch", 0, "1970-01-01T00:00:00.000Z"),
    ("billennium", 1000000000000000000, "2001-09-09T01:46:40.000Z"),
    ("with-milliseconds", 1710054000123456789, "2024-03-10T07:00:00.123Z"),
    ("leap-day", 1709208000000000000, "2024-02-29T12:00:00.000Z"),
    ("truncate-not-round", 999999, "1970-01-01T00:00:00.000Z"),
    ("one-ns-before-epoch", -1, "1969-12-31T23:59:59.999Z"),
    ("one-ms-before-epoch", -1000000, "1969-12-31T23:59:59.999Z"),
    ("just-over-one-ms-before-epoch", -1000001, "1969-12-31T23:59:59.998Z"),
    ("last-ms-of-a-year", 1704067199999999999, "2023-12-31T23:59:59.999Z"),
    ("year-2000-is-leap", 951782400000000000, "2000-02-29T00:00:00.000Z"),
    ("year-2100-is-not-leap", 4107542399999999999, "2100-02-28T23:59:59.999Z"),
    ("after-int32-seconds", 2147483648000000000, "2038-01-19T03:14:08.000Z"),
    ("int64-max", 9223372036854775807, "2262-04-11T23:47:16.854Z"),
    ("int64-min", i64::MIN, "1677-09-21T00:12:43.145Z"),
];

#[test]
fn utc_timestamp_cases() {
    for &(name, epoch_ns, want) in CASES {
        assert_eq!(utc_timestamp(epoch_ns), want, "{name}");
    }
}

#[test]
fn now_utc_with_a_fake_clock() {
    let mut calls = 0;
    let got = now_utc(|| {
        calls += 1;
        1_710_054_000_123_456_789
    });
    assert_eq!(got, "2024-03-10T07:00:00.123Z");
    assert_eq!(calls, 1);
}

#[test]
fn now_utc_with_the_real_clock() {
    let got = now_utc(system_ns);
    let b = got.as_bytes();
    assert_eq!(b.len(), 24, "{got}");
    assert!(b[10] == b'T' && b[19] == b'.' && b[23] == b'Z', "{got}");
    assert!(got[..4].parse::<i32>().unwrap() >= 2024, "{got}");
}
now.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-current-date-and-time/.

# system_ns prints the system clock in nanoseconds since 1970-01-01T00:00:00Z.
# EPOCHREALTIME has microseconds, and its decimal point comes from the locale,
# so the code removes every character that is not a digit.
system_ns() {
  local us=${EPOCHREALTIME//[!0-9]/}
  printf '%s\n' "$((10#$us * 1000))"
}

# utc_timestamp NS prints the UTC date and time of NS nanoseconds since the
# epoch as YYYY-MM-DDTHH:MM:SS.mmmZ. It needs GNU date for -d @SECONDS.
utc_timestamp() {
  local ns=$1 ms secs date
  # The / of Bash rounds toward zero. Step back for a negative rest, so the
  # result goes toward the past.
  ms=$((ns / 1000000))
  if ((ns % 1000000 < 0)); then ((ms -= 1)); fi
  secs=$((ms / 1000))
  if ((ms % 1000 < 0)); then ((secs -= 1)); fi
  date=$(date -u -d "@$secs" +%Y-%m-%dT%H:%M:%S) || return
  printf '%s.%03dZ\n' "$date" "$((ms - secs * 1000))"
}

# now_utc [CLOCK] reads CLOCK once and prints the UTC date and time of the
# reading. CLOCK is a command that prints nanoseconds; system_ns is the real one.
now_utc() {
  local ns
  ns=$("${1:-system_ns}") || return
  utc_timestamp "$ns"
}
test_now.bats 50 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-current-date-and-time/.

setup() {
  source "$BATS_TEST_DIRNAME/now.sh"
}

@test "epoch" { run utc_timestamp 0; [ "$status" -eq 0 ]; [ "$output" = "1970-01-01T00:00:00.000Z" ]; }
@test "billennium" { run utc_timestamp 1000000000000000000; [ "$status" -eq 0 ]; [ "$output" = "2001-09-09T01:46:40.000Z" ]; }
@test "with-milliseconds" { run utc_timestamp 1710054000123456789; [ "$status" -eq 0 ]; [ "$output" = "2024-03-10T07:00:00.123Z" ]; }
@test "leap-day" { run utc_timestamp 1709208000000000000; [ "$status" -eq 0 ]; [ "$output" = "2024-02-29T12:00:00.000Z" ]; }
@test "truncate-not-round" { run utc_timestamp 999999; [ "$status" -eq 0 ]; [ "$output" = "1970-01-01T00:00:00.000Z" ]; }
@test "one-ns-before-epoch" { run utc_timestamp -1; [ "$status" -eq 0 ]; [ "$output" = "1969-12-31T23:59:59.999Z" ]; }
@test "one-ms-before-epoch" { run utc_timestamp -1000000; [ "$status" -eq 0 ]; [ "$output" = "1969-12-31T23:59:59.999Z" ]; }
@test "just-over-one-ms-before-epoch" { run utc_timestamp -1000001; [ "$status" -eq 0 ]; [ "$output" = "1969-12-31T23:59:59.998Z" ]; }
@test "last-ms-of-a-year" { run utc_timestamp 1704067199999999999; [ "$status" -eq 0 ]; [ "$output" = "2023-12-31T23:59:59.999Z" ]; }
@test "year-2000-is-leap" { run utc_timestamp 951782400000000000; [ "$status" -eq 0 ]; [ "$output" = "2000-02-29T00:00:00.000Z" ]; }
@test "year-2100-is-not-leap" { run utc_timestamp 4107542399999999999; [ "$status" -eq 0 ]; [ "$output" = "2100-02-28T23:59:59.999Z" ]; }
@test "after-int32-seconds" { run utc_timestamp 2147483648000000000; [ "$status" -eq 0 ]; [ "$output" = "2038-01-19T03:14:08.000Z" ]; }
@test "int64-max" { run utc_timestamp 9223372036854775807; [ "$status" -eq 0 ]; [ "$output" = "2262-04-11T23:47:16.854Z" ]; }
@test "int64-min" { run utc_timestamp -9223372036854775808; [ "$status" -eq 0 ]; [ "$output" = "1677-09-21T00:12:43.145Z" ]; }

# fake_clock prints one fixed reading and logs the call. now_utc runs the clock
# in a command substitution, so the log is a file.
fake_clock() {
  echo clock >>"$BATS_TEST_TMPDIR/calls"
  echo 1710054000123456789
}

@test "now_utc with a fake clock" {
  run now_utc fake_clock
  [ "$status" -eq 0 ]
  [ "$output" = "2024-03-10T07:00:00.123Z" ]
  [ "$(<"$BATS_TEST_TMPDIR/calls")" = "clock" ]
}

@test "now_utc with the real clock" {
  run now_utc
  [ "$status" -eq 0 ]
  [[ "$output" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$ ]]
  [ "${output:0:4}" -ge 2024 ]
}

@test "system_ns prints whole nanoseconds after 2024" {
  run system_ns
  [ "$status" -eq 0 ]
  [[ "$output" =~ ^[0-9]+000$ ]]
  ((output >= 1704067200000000000))
}

References

  1. The Python Standard Library, datetime, datetime.now, datetime.utcnow, Aware and naive objects
  2. The Python Standard Library, time, time.time, time.time_ns
  3. MDN Web Docs, Date.now(), Description, Reduced time precision
  4. MDN Web Docs, Date.prototype.toISOString(), Description
  5. TC39 Temporal proposal, Temporal.Now, Temporal.Now.instant, Temporal.Now.zonedDateTimeISO, Temporal.Now.timeZoneId
  6. Java SE 25 API, java.time.Clock, Class description; systemUTC(); fixed(Instant, ZoneId)
  7. Java SE 25 API, java.time.Instant, now(); toString(); truncatedTo(TemporalUnit)
  8. .NET API reference, DateTimeOffset.UtcNow, Remarks
  9. .NET API reference, DateTime.Now, Remarks
  10. .NET API reference, TimeProvider, Remarks; Properties (System); Methods (GetUtcNow, GetLocalNow)
  11. Go standard library, time, func Now; Monotonic Clocks; Constants (layouts); func (Time) Equal
  12. The Rust Standard Library, std::time::SystemTime, Description; now; duration_since; UNIX_EPOCH
  13. The Open Group Base Specifications Issue 8, clock_getres, clock_gettime, clock_settime, DESCRIPTION, CLOCK_REALTIME
  14. The Open Group Base Specifications Issue 8, gmtime, gmtime_r, DESCRIPTION; RETURN VALUE
  15. cppreference.com, timespec_get, the description of the function
  16. cppreference.com, std::chrono::system_clock, the description of the class
  17. cppreference.com, std::formatter<std::chrono::sys_time>, Format specification, %S and %T
  18. Bash Reference Manual, 5.2 Bash Variables: EPOCHREALTIME, EPOCHSECONDS; 4.2 Bash Builtin Commands: printf, %(datefmt)T
  19. Linux manual page, date(1), DESCRIPTION; EXAMPLES

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source