Programming Search⌘K

Taskintro

Get a Unix timestamp

Also called unix timestamp, epoch time, epoch seconds, epoch milliseconds, seconds since the epoch, posix time, current timestamp, date to timestamp, timestamp to date.

Get the seconds or milliseconds since 1970-01-01T00:00:00Z as an integer, and convert a date, a time and a UTC offset to that number and back without the local zone of the system.

Task

Get a Unix timestamp: the number of seconds since 1970-01-01T00:00:00Z, without leap seconds. Many programs and formats store a time as this integer, or as the number of milliseconds since the same instant. Get the timestamp of the current time, and convert a date and a time of day to a timestamp and back.

The real time changes on each run, so the contract tests the conversion. unix_timestamp(year, month, day, hour, minute, second, offset_minutes) takes a local date and time and its UTC offset in minutes, positive east of Greenwich, and returns the timestamp in seconds. The offset is part of the input, so the result does not depend on the time zone of the system. A time before 1970 gives a negative timestamp. The years are 1 to 9999 in the proleptic Gregorian calendar.

Each solution also has now_unix_seconds() and now_unix_millis(). They read the system clock and round toward the past. The tests check that both values are in 2024 or later and that they agree. The tests also convert each expected timestamp back to a date with the date type of the language.

Solutions

POSIX defines "Seconds Since the Epoch" with a formula from the fields of a UTC date. Each day has exactly 86400 seconds in this count, so a leap second has no number of its own (see Leap seconds). Each solution below keeps the timestamp as an integer. A timestamp in seconds is in the range of a signed 64-bit integer for each year of the contract.

  • Python. time.time() returns the current time in seconds as a float, and time.time_ns() returns it in nanoseconds as an int. time.time_ns() // 1_000_000_000 gives whole seconds, rounded toward the past. datetime.timestamp() also returns a float, and it treats a naive datetime as local time. The solution subtracts the epoch from an aware datetime and divides by timedelta(seconds=1), which gives an int. calendar.timegm(t) converts a UTC time tuple to a timestamp, and datetime.fromtimestamp(s, timezone.utc) converts back.
  • JavaScript. A Date holds the number of milliseconds since the epoch, and Date.now() and getTime() return it. Divide by 1000 and use Math.floor to get whole seconds. Date.UTC(year, monthIndex, ...) reads the years 0 to 99 as 1900 to 1999, and its month starts at 0. The solution calls setUTCFullYear and setUTCHours on a Date, which take the year as it is. The minutes argument can be negative or over 59, so it also subtracts the offset. new Date(seconds * 1000) converts back.
  • TypeScript. The same code as JavaScript, with the type number.
  • Java. Instant.now().getEpochSecond() gives whole seconds, and System.currentTimeMillis() and Instant.toEpochMilli() give milliseconds. OffsetDateTime.of(...).toEpochSecond() converts a date, a time and a ZoneOffset to seconds. Instant.ofEpochSecond(s) converts back, and atOffset(offset) gives the local date and time again.
  • C#. DateTimeOffset.UtcNow.ToUnixTimeSeconds() and ToUnixTimeMilliseconds() give the current timestamp. new DateTimeOffset(year, month, day, hour, minute, second, offset) holds the offset, and ToUnixTimeSeconds() converts it to UTC first. DateTimeOffset.FromUnixTimeSeconds(s) converts back, and it accepts -62,135,596,800 to 253,402,300,799: the years 1 to 9999.
  • Go. time.Now().Unix() and time.Now().UnixMilli() give the current timestamp. time.Date(year, month, day, hour, minute, second, 0, loc) with time.FixedZone("", offset) makes a time with a fixed offset, and Unix() converts it. time.Unix(s, 0) and time.UnixMilli(ms) convert back.
  • Rust. SystemTime::now().duration_since(UNIX_EPOCH) returns a Duration, or an error if the clock is before 1970. as_secs() and as_millis() give whole units. The standard library has no calendar type, so the solution converts the date to days with the days_from_civil algorithm of Howard Hinnant. A crate such as chrono or jiff has calendar types.
  • C. time(NULL) returns the current time in seconds since the epoch as a time_t, and timespec_get(&ts, TIME_UTC) adds nanoseconds. mktime reads a struct tm as local time. timegm reads it as UTC, and C23 added it to the standard. Both work in time_t, and the range of time_t and of these functions depends on the system. The solution computes the days with days_from_civil and needs only 64-bit integers. gmtime_r converts a timestamp back to a struct tm.
  • C++. std::chrono::system_clock measures Unix time. floor<seconds>(system_clock::now()).time_since_epoch().count() gives whole seconds. A year_month_day converts to sys_days, a count of days since the epoch, and the solution adds the hours, the minutes and the seconds to it. std::format("{:%FT%T}", t) writes a sys_seconds back as a date.
  • Bash. $EPOCHSECONDS expands to the current time in whole seconds, and $EPOCHREALTIME to seconds with microseconds. date +%s prints the same number. GNU date -u -d '2024-03-10T02:00:00-05:00' +%s converts a date with an offset, and date -u -d @1710054000 converts back.

A timestamp is the same number in each time zone. Only its conversion to a date and a time of day needs a zone:

from datetime import datetime, timedelta, timezone

EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
new_york = datetime(2024, 3, 10, 2, 0, tzinfo=timezone(timedelta(hours=-5)))
tokyo = datetime(2024, 3, 10, 16, 0, tzinfo=timezone(timedelta(hours=9)))
print((new_york - EPOCH) // timedelta(seconds=1))
print((tokyo - EPOCH) // timedelta(seconds=1))
print(datetime.fromtimestamp(1710054000, timezone.utc).isoformat())
Output
1710054000
1710054000
2024-03-10T07:00:00+00:00

Edge cases

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

  • epoch and billennium: 1970-01-01T00:00:00Z is 0, and 2001-09-09T01:46:40Z is 1000000000.
  • negative-offset and positive-offset: 2024-03-10T02:00:00-05:00 and 2024-03-10T16:00:00+09:00 are the same instant, 1710054000.
  • one-second-before-epoch and offset-moves-before-epoch: 1969-12-31T23:59:59Z is -1, and 1970-01-01T00:00:00+01:00 is -3600.
  • offset-moves-to-next-year, offset-of-45-minutes and offset-of-minus-9-30: an offset can move the UTC time to another year, and an offset can have 30 or 45 minutes.
  • offset-plus-14 and offset-minus-12: the offsets +14:00 and -12:00 also give 0 at the epoch.
  • leap-day, year-2000-is-leap and year-1900-is-not-leap: the year 1900 has no February 29, so 1900-03-01 is -2203891200.
  • int32-max, after-int32-max and int32-min: 2038-01-19T03:14:07Z is 2147483647, the largest value of a signed 32-bit integer. One second later needs more than 32 bits. 1901-12-13T20:45:52Z is -2147483648.
  • year-99-is-not-1999: the year 99 is -59011459201. Date.UTC in JavaScript gives the year 1999 for it.
  • first-second-of-year-1 and last-second-of-year-9999: -62135596800 and 253402300799, the range of .NET DateTimeOffset.

Pitfalls

  • Seconds and milliseconds are both called a timestamp. JavaScript, Java currentTimeMillis and Go UnixMilli use milliseconds. Most of the other functions on this page use seconds. A value in the wrong unit gives a date near 1970 or a date thousands of years later:

This code runs but gives a wrong answer on purpose.

const seconds = 1710054000;
console.log(new Date(seconds).toISOString());
console.log(new Date(seconds * 1000).toISOString());
console.log(Date.UTC(99, 11, 31) / 1000);
Output
1970-01-20T19:00:54.000Z
2024-03-10T07:00:00.000Z
946598400

The last line also shows that Date.UTC reads the year 99 as 1999.

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"time"
)

func main() {
	millis := int64(1710054000123)
	fmt.Println(time.Unix(millis, 0).UTC().Year())
	fmt.Println(time.UnixMilli(millis).UTC().Format(time.RFC3339Nano))
}
Output
56159
2024-03-10T07:00:00.123Z
  • mktime and naive values use the local zone. C mktime, Python time.mktime and Python datetime.timestamp() with a naive datetime read the fields as local time. The result changes with the time zone of the system. Use calendar.timegm, or an aware datetime:

This code runs but gives a wrong answer on purpose.

import calendar
import os
import time

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

fields = (2024, 1, 1, 0, 0, 0, 0, 1, 0)
print("mktime:", time.mktime(fields))
print("timegm:", calendar.timegm(fields))
Output
mktime: 1704085200.0
timegm: 1704067200

The same mistake in Bash: date -d reads a date with no offset as local time.

This code runs but gives a wrong answer on purpose.

TZ=America/New_York date -d '2024-01-01 00:00' +%s
TZ=America/New_York date -d '2024-01-01T00:00:00Z' +%s
date -u -d '2024-01-01 00:00' +%s
Output
1704085200
1704067200
1704067200
  • A float of seconds loses digits. A 64-bit float has about 16 significant decimal digits, and a timestamp in seconds already uses 10 of them. It cannot hold nanoseconds. Keep an integer, such as the result of time.time_ns():

This code runs but gives a wrong answer on purpose.

ns = 1710054000123456789
seconds = ns / 1e9
print(seconds)
print(int(seconds * 1e9))
print(divmod(ns, 10**9))
Output
1710054000.1234567
1710054000123456768
(1710054000, 123456789)
  • Integer division of a negative timestamp goes toward zero. In Java, C, C++, C#, Go and Rust, / on integers drops the fraction toward zero. For a time before 1970, milliseconds divided by 1000 give the next second, not the second that contains the time. Use Math.floorDiv, div_euclid, or a library function:

This code runs but gives a wrong answer on purpose.

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        long millis = -1500L; // 1969-12-31T23:59:58.500Z
        System.out.println(millis / 1000);
        System.out.println(Math.floorDiv(millis, 1000L));
        System.out.println(Instant.ofEpochMilli(millis).getEpochSecond());
    }
}
Output
-1
-2
-2

ToUnixTimeSeconds in .NET returns the second that contains the time:

var t = new DateTimeOffset(1969, 12, 31, 23, 59, 58, 500, TimeSpan.Zero);
Console.WriteLine(t.ToUnixTimeMilliseconds());
Console.WriteLine(t.ToUnixTimeSeconds());
Console.WriteLine(t.ToUnixTimeMilliseconds() / 1000);
Output
-1500
-2
-1
  • A 32-bit timestamp ends in 2038. A signed 32-bit integer holds the timestamps up to 2038-01-19T03:14:07Z. One second later, the bits of the next value are the bits of -2147483648, which is a time in 1901. Use a 64-bit type for a timestamp, also in files and in database columns:

This code runs but gives a wrong answer on purpose.

#define _DEFAULT_SOURCE
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

int main(void) {
    uint32_t bits = UINT32_C(2147483648); // 2038-01-19T03:14:08Z
    int32_t stored;
    memcpy(&stored, &bits, sizeof stored);
    time_t t = stored;
    struct tm tm;
    char text[32];
    gmtime_r(&t, &tm);
    strftime(text, sizeof text, "%Y-%m-%dT%H:%M:%SZ", &tm);
    printf("%" PRId32 " %s\n", stored, text);
}
Output
-2147483648 1901-12-13T20:45:52Z
  • A timestamp has no leap seconds. A difference of two timestamps across a leap second is one second short of the real elapsed time. Measure a duration with a monotonic clock (see Measure elapsed time).

See Unix time for the definition and the history of the count.

Code

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

unix.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-unix-timestamp/.

import time
from datetime import datetime, timedelta, timezone

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


def unix_timestamp(
    year: int, month: int, day: int, hour: int, minute: int, second: int, offset_minutes: int
) -> int:
    """Return the seconds since 1970-01-01T00:00:00Z of a local time with the given UTC offset."""
    zone = timezone(timedelta(minutes=offset_minutes))
    moment = datetime(year, month, day, hour, minute, second, tzinfo=zone)
    # Integer division of two timedeltas gives an int. moment.timestamp() gives a float.
    return (moment - EPOCH) // timedelta(seconds=1)


def now_unix_seconds() -> int:
    """Return the current Unix time in whole seconds, rounded toward the past."""
    return time.time_ns() // 1_000_000_000


def now_unix_millis() -> int:
    """Return the current Unix time in whole milliseconds, rounded toward the past."""
    return time.time_ns() // 1_000_000
test_unix.py 51 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-unix-timestamp/.

from datetime import datetime, timedelta, timezone

import pytest

from unix import now_unix_millis, now_unix_seconds, unix_timestamp

CASES = [
    ("epoch", (1970, 1, 1, 0, 0, 0, 0), 0),
    ("billennium", (2001, 9, 9, 1, 46, 40, 0), 1000000000),
    ("negative-offset", (2024, 3, 10, 2, 0, 0, -300), 1710054000),
    ("positive-offset", (2024, 3, 10, 16, 0, 0, 540), 1710054000),
    ("one-second-before-epoch", (1969, 12, 31, 23, 59, 59, 0), -1),
    ("offset-moves-before-epoch", (1970, 1, 1, 0, 0, 0, 60), -3600),
    ("offset-moves-to-next-year", (2023, 12, 31, 19, 0, 0, -300), 1704067200),
    ("offset-of-45-minutes", (2024, 1, 1, 5, 45, 0, 345), 1704067200),
    ("offset-of-minus-9-30", (2023, 12, 31, 14, 30, 0, -570), 1704067200),
    ("offset-plus-14", (1970, 1, 1, 14, 0, 0, 840), 0),
    ("offset-minus-12", (1969, 12, 31, 12, 0, 0, -720), 0),
    ("leap-day", (2024, 2, 29, 0, 0, 0, 0), 1709164800),
    ("year-2000-is-leap", (2000, 2, 29, 0, 0, 0, 0), 951782400),
    ("year-1900-is-not-leap", (1900, 3, 1, 0, 0, 0, 0), -2203891200),
    ("int32-max", (2038, 1, 19, 3, 14, 7, 0), 2147483647),
    ("after-int32-max", (2038, 1, 19, 3, 14, 8, 0), 2147483648),
    ("int32-min", (1901, 12, 13, 20, 45, 52, 0), -2147483648),
    ("year-99-is-not-1999", (99, 12, 31, 23, 59, 59, 0), -59011459201),
    ("first-second-of-year-1", (1, 1, 1, 0, 0, 0, 0), -62135596800),
    ("last-second-of-year-9999", (9999, 12, 31, 23, 59, 59, 0), 253402300799),
]


@pytest.mark.parametrize(("name", "fields", "want"), CASES, ids=[c[0] for c in CASES])
def test_unix_timestamp(name, fields, want):
    assert unix_timestamp(*fields) == want


@pytest.mark.parametrize(("name", "fields", "want"), CASES, ids=[c[0] for c in CASES])
def test_back_to_a_date(name, fields, want):
    *date, offset = fields
    zone = timezone(timedelta(minutes=offset))
    assert datetime.fromtimestamp(0, timezone.utc) + timedelta(seconds=want) == datetime(*date, tzinfo=zone)


def test_now():
    seconds = now_unix_seconds()
    millis = now_unix_millis()
    assert seconds >= 1_704_067_200
    assert 0 <= millis // 1000 - seconds <= 1
    assert datetime.fromtimestamp(seconds, timezone.utc).year >= 2024
unix.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

#pragma once

#include <chrono>
#include <cstdint>

// Returns the seconds since 1970-01-01T00:00:00Z of a local time with the
// given UTC offset in minutes.
inline std::int64_t unix_timestamp(int year, int month, int day, int hour, int minute, int second,
                                   int offset_minutes) {
    using namespace std::chrono;
    const sys_days date = std::chrono::year{year} / month / day;
    const sys_seconds utc = date + hours{hour} + minutes{minute - offset_minutes} + seconds{second};
    return utc.time_since_epoch().count();
}

// Returns the current Unix time in whole seconds, rounded toward the past.
inline std::int64_t now_unix_seconds() {
    using namespace std::chrono;
    return floor<seconds>(system_clock::now()).time_since_epoch().count();
}

// Returns the current Unix time in whole milliseconds, rounded toward the past.
inline std::int64_t now_unix_millis() {
    using namespace std::chrono;
    return floor<milliseconds>(system_clock::now()).time_since_epoch().count();
}
test_unix.cpp 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

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

#include "unix.hpp"

namespace {

struct test_case {
    const char* name;
    int year, month, day, hour, minute, second, offset;
    long long want;
};

const test_case cases[] = {
    {"epoch", 1970, 1, 1, 0, 0, 0, 0, 0LL},
    {"billennium", 2001, 9, 9, 1, 46, 40, 0, 1000000000LL},
    {"negative-offset", 2024, 3, 10, 2, 0, 0, -300, 1710054000LL},
    {"positive-offset", 2024, 3, 10, 16, 0, 0, 540, 1710054000LL},
    {"one-second-before-epoch", 1969, 12, 31, 23, 59, 59, 0, -1LL},
    {"offset-moves-before-epoch", 1970, 1, 1, 0, 0, 0, 60, -3600LL},
    {"offset-moves-to-next-year", 2023, 12, 31, 19, 0, 0, -300, 1704067200LL},
    {"offset-of-45-minutes", 2024, 1, 1, 5, 45, 0, 345, 1704067200LL},
    {"offset-of-minus-9-30", 2023, 12, 31, 14, 30, 0, -570, 1704067200LL},
    {"offset-plus-14", 1970, 1, 1, 14, 0, 0, 840, 0LL},
    {"offset-minus-12", 1969, 12, 31, 12, 0, 0, -720, 0LL},
    {"leap-day", 2024, 2, 29, 0, 0, 0, 0, 1709164800LL},
    {"year-2000-is-leap", 2000, 2, 29, 0, 0, 0, 0, 951782400LL},
    {"year-1900-is-not-leap", 1900, 3, 1, 0, 0, 0, 0, -2203891200LL},
    {"int32-max", 2038, 1, 19, 3, 14, 7, 0, 2147483647LL},
    {"after-int32-max", 2038, 1, 19, 3, 14, 8, 0, 2147483648LL},
    {"int32-min", 1901, 12, 13, 20, 45, 52, 0, -2147483648LL},
    {"year-99-is-not-1999", 99, 12, 31, 23, 59, 59, 0, -59011459201LL},
    {"first-second-of-year-1", 1, 1, 1, 0, 0, 0, 0, -62135596800LL},
    {"last-second-of-year-9999", 9999, 12, 31, 23, 59, 59, 0, 253402300799LL},
};

int failures = 0;

void expect(bool ok, const char* what, const char* name) {
    if (!ok) {
        std::printf("FAIL %s: %s\n", name, what);
        ++failures;
    }
}

}  // namespace

int main() {
    using namespace std::chrono;
    for (const auto& c : cases) {
        expect(unix_timestamp(c.year, c.month, c.day, c.hour, c.minute, c.second, c.offset) == c.want,
               "unix_timestamp", c.name);
        const sys_seconds back{seconds{c.want}};
        const auto local = back + minutes{c.offset};
        const std::string text = std::format("{:%FT%T}", local);
        const std::string want = std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", c.year, c.month, c.day, c.hour,
                                             c.minute, c.second);
        expect(text == want, "back to a date", c.name);
    }

    const auto secs = now_unix_seconds();
    const auto millis = now_unix_millis();
    expect(secs >= 1704067200, "now_unix_seconds is in 2024 or later", "now");
    const auto diff = millis / 1000 - secs;
    expect(diff >= 0 && diff <= 1, "seconds and milliseconds agree", "now");

    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
UnixTime.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public final class UnixTime {
    private UnixTime() {}

    /** Returns the seconds since 1970-01-01T00:00:00Z of a local time with the given UTC offset. */
    public static long unixTimestamp(
            int year, int month, int day, int hour, int minute, int second, int offsetMinutes) {
        ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetMinutes * 60);
        return OffsetDateTime.of(year, month, day, hour, minute, second, 0, offset).toEpochSecond();
    }

    /** Returns the current Unix time in whole seconds, rounded toward the past. */
    public static long nowUnixSeconds() {
        return Instant.now().getEpochSecond();
    }

    /** Returns the current Unix time in milliseconds. */
    public static long nowUnixMillis() {
        return System.currentTimeMillis();
    }
}
UnixTimeTest.java 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

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

import java.time.Instant;
import java.time.OffsetDateTime;
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 UnixTimeTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("epoch", 1970, 1, 1, 0, 0, 0, 0, 0L),
                Arguments.of("billennium", 2001, 9, 9, 1, 46, 40, 0, 1000000000L),
                Arguments.of("negative-offset", 2024, 3, 10, 2, 0, 0, -300, 1710054000L),
                Arguments.of("positive-offset", 2024, 3, 10, 16, 0, 0, 540, 1710054000L),
                Arguments.of("one-second-before-epoch", 1969, 12, 31, 23, 59, 59, 0, -1L),
                Arguments.of("offset-moves-before-epoch", 1970, 1, 1, 0, 0, 0, 60, -3600L),
                Arguments.of("offset-moves-to-next-year", 2023, 12, 31, 19, 0, 0, -300, 1704067200L),
                Arguments.of("offset-of-45-minutes", 2024, 1, 1, 5, 45, 0, 345, 1704067200L),
                Arguments.of("offset-of-minus-9-30", 2023, 12, 31, 14, 30, 0, -570, 1704067200L),
                Arguments.of("offset-plus-14", 1970, 1, 1, 14, 0, 0, 840, 0L),
                Arguments.of("offset-minus-12", 1969, 12, 31, 12, 0, 0, -720, 0L),
                Arguments.of("leap-day", 2024, 2, 29, 0, 0, 0, 0, 1709164800L),
                Arguments.of("year-2000-is-leap", 2000, 2, 29, 0, 0, 0, 0, 951782400L),
                Arguments.of("year-1900-is-not-leap", 1900, 3, 1, 0, 0, 0, 0, -2203891200L),
                Arguments.of("int32-max", 2038, 1, 19, 3, 14, 7, 0, 2147483647L),
                Arguments.of("after-int32-max", 2038, 1, 19, 3, 14, 8, 0, 2147483648L),
                Arguments.of("int32-min", 1901, 12, 13, 20, 45, 52, 0, -2147483648L),
                Arguments.of("year-99-is-not-1999", 99, 12, 31, 23, 59, 59, 0, -59011459201L),
                Arguments.of("first-second-of-year-1", 1, 1, 1, 0, 0, 0, 0, -62135596800L),
                Arguments.of("last-second-of-year-9999", 9999, 12, 31, 23, 59, 59, 0, 253402300799L)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void unixTimestamp(
            String name, int year, int month, int day, int hour, int minute, int second, int offset, long want) {
        assertEquals(want, UnixTime.unixTimestamp(year, month, day, hour, minute, second, offset));
        OffsetDateTime back = Instant.ofEpochSecond(want).atOffset(ZoneOffset.ofTotalSeconds(offset * 60));
        assertEquals(OffsetDateTime.of(year, month, day, hour, minute, second, 0, back.getOffset()), back);
    }

    @Test
    void integerDivisionOfMillisTruncatesTowardZero() {
        assertEquals(-1L, -1500L / 1000L);
        assertEquals(-2L, Math.floorDiv(-1500L, 1000L));
        assertEquals(-2L, Instant.ofEpochMilli(-1500L).getEpochSecond());
    }

    @Test
    void now() {
        long seconds = UnixTime.nowUnixSeconds();
        long millis = UnixTime.nowUnixMillis();
        assertTrue(seconds >= 1_704_067_200L);
        long diff = Math.floorDiv(millis, 1000L) - seconds;
        assertTrue(diff >= 0 && diff <= 1);
    }
}
unix.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

#include "unix.h"

#include <time.h>

// Returns the number of days from 1970-01-01 to a date in the proleptic
// Gregorian calendar (the days_from_civil algorithm of Howard Hinnant).
static int64_t days_from_civil(int64_t year, int64_t month, int64_t day) {
    int64_t y = month <= 2 ? year - 1 : year;
    int64_t era = (y >= 0 ? y : y - 399) / 400;  // division toward the past
    int64_t yoe = y - era * 400;                  // 0 to 399
    int64_t mp = (month + 9) % 12;                // March is 0
    int64_t doy = (153 * mp + 2) / 5 + day - 1;   // 0 to 365
    int64_t doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    return era * 146097 + doe - 719468;
}

int64_t unix_timestamp(int year, int month, int day, int hour, int minute, int second, int offset_minutes) {
    // timegm and mktime need a time_t, and the range of time_t and of these
    // functions depends on the system. The arithmetic below has no such limit.
    return days_from_civil(year, month, day) * 86400 + (int64_t)hour * 3600 +
           ((int64_t)minute - offset_minutes) * 60 + second;
}

int64_t now_unix_seconds(void) {
    return (int64_t)time(NULL);
}

int64_t now_unix_millis(void) {
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    int64_t millis = (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
    return millis;
}
unix.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

#ifndef UNIX_TIMESTAMP_H
#define UNIX_TIMESTAMP_H

#include <stdint.h>

// Returns the seconds since 1970-01-01T00:00:00Z of a local time with the
// given UTC offset in minutes.
int64_t unix_timestamp(int year, int month, int day, int hour, int minute, int second, int offset_minutes);

// Returns the current Unix time in whole seconds.
int64_t now_unix_seconds(void);

// Returns the current Unix time in whole milliseconds, rounded toward the past.
int64_t now_unix_millis(void);

#endif
test_unix.c 82 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

#define _DEFAULT_SOURCE

#include "unix.h"

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

struct test_case {
    const char *name;
    int year, month, day, hour, minute, second, offset;
    long long want;
};

static const struct test_case cases[] = {
    {"epoch", 1970, 1, 1, 0, 0, 0, 0, 0LL},
    {"billennium", 2001, 9, 9, 1, 46, 40, 0, 1000000000LL},
    {"negative-offset", 2024, 3, 10, 2, 0, 0, -300, 1710054000LL},
    {"positive-offset", 2024, 3, 10, 16, 0, 0, 540, 1710054000LL},
    {"one-second-before-epoch", 1969, 12, 31, 23, 59, 59, 0, -1LL},
    {"offset-moves-before-epoch", 1970, 1, 1, 0, 0, 0, 60, -3600LL},
    {"offset-moves-to-next-year", 2023, 12, 31, 19, 0, 0, -300, 1704067200LL},
    {"offset-of-45-minutes", 2024, 1, 1, 5, 45, 0, 345, 1704067200LL},
    {"offset-of-minus-9-30", 2023, 12, 31, 14, 30, 0, -570, 1704067200LL},
    {"offset-plus-14", 1970, 1, 1, 14, 0, 0, 840, 0LL},
    {"offset-minus-12", 1969, 12, 31, 12, 0, 0, -720, 0LL},
    {"leap-day", 2024, 2, 29, 0, 0, 0, 0, 1709164800LL},
    {"year-2000-is-leap", 2000, 2, 29, 0, 0, 0, 0, 951782400LL},
    {"year-1900-is-not-leap", 1900, 3, 1, 0, 0, 0, 0, -2203891200LL},
    {"int32-max", 2038, 1, 19, 3, 14, 7, 0, 2147483647LL},
    {"after-int32-max", 2038, 1, 19, 3, 14, 8, 0, 2147483648LL},
    {"int32-min", 1901, 12, 13, 20, 45, 52, 0, -2147483648LL},
    {"year-99-is-not-1999", 99, 12, 31, 23, 59, 59, 0, -59011459201LL},
    {"first-second-of-year-1", 1, 1, 1, 0, 0, 0, 0, -62135596800LL},
    {"last-second-of-year-9999", 9999, 12, 31, 23, 59, 59, 0, 253402300799LL},
};

static int failures = 0;

static void expect(int ok, const char *what, const char *name) {
    if (!ok) {
        printf("FAIL %s: %s\n", name, what);
        failures++;
    }
}

int main(void) {
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int64_t got = unix_timestamp(c->year, c->month, c->day, c->hour, c->minute, c->second, c->offset);
        expect(got == c->want, "unix_timestamp", c->name);

        time_t back = (time_t)(c->want + (int64_t)c->offset * 60);
        struct tm tm;
        char text[96], want_text[96];
        if (gmtime_r(&back, &tm) == NULL) {
            expect(0, "gmtime_r", c->name);
            continue;
        }
        snprintf(text, sizeof text, "%04d-%02d-%02dT%02d:%02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
                 tm.tm_hour, tm.tm_min, tm.tm_sec);
        snprintf(want_text, sizeof want_text, "%04d-%02d-%02dT%02d:%02d:%02d", c->year, c->month, c->day, c->hour,
                 c->minute, c->second);
        expect(strcmp(text, want_text) == 0, "back to a date", c->name);
    }

    int64_t seconds = now_unix_seconds();
    int64_t millis = now_unix_millis();
    expect(seconds >= 1704067200, "now_unix_seconds is in 2024 or later", "now");
    int64_t diff = millis / 1000 - seconds;
    expect(diff >= 0 && diff <= 1, "seconds and milliseconds agree", "now");

    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
UnixTime.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

public static class UnixTime
{
    /// <summary>Returns the seconds since 1970-01-01T00:00:00Z of a local time with the given UTC offset.</summary>
    public static long UnixTimestamp(int year, int month, int day, int hour, int minute, int second, int offsetMinutes)
    {
        var offset = TimeSpan.FromMinutes(offsetMinutes);
        return new DateTimeOffset(year, month, day, hour, minute, second, offset).ToUnixTimeSeconds();
    }

    /// <summary>Returns the current Unix time in whole seconds.</summary>
    public static long NowUnixSeconds() => DateTimeOffset.UtcNow.ToUnixTimeSeconds();

    /// <summary>Returns the current Unix time in whole milliseconds.</summary>
    public static long NowUnixMillis() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
UnixTimeTests.cs 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

using Xunit;

public sealed class UnixTimeTests
{
    public static TheoryData<string, int, int, int, int, int, int, int, long> Cases => new()
    {
        { "epoch", 1970, 1, 1, 0, 0, 0, 0, 0L },
        { "billennium", 2001, 9, 9, 1, 46, 40, 0, 1000000000L },
        { "negative-offset", 2024, 3, 10, 2, 0, 0, -300, 1710054000L },
        { "positive-offset", 2024, 3, 10, 16, 0, 0, 540, 1710054000L },
        { "one-second-before-epoch", 1969, 12, 31, 23, 59, 59, 0, -1L },
        { "offset-moves-before-epoch", 1970, 1, 1, 0, 0, 0, 60, -3600L },
        { "offset-moves-to-next-year", 2023, 12, 31, 19, 0, 0, -300, 1704067200L },
        { "offset-of-45-minutes", 2024, 1, 1, 5, 45, 0, 345, 1704067200L },
        { "offset-of-minus-9-30", 2023, 12, 31, 14, 30, 0, -570, 1704067200L },
        { "offset-plus-14", 1970, 1, 1, 14, 0, 0, 840, 0L },
        { "offset-minus-12", 1969, 12, 31, 12, 0, 0, -720, 0L },
        { "leap-day", 2024, 2, 29, 0, 0, 0, 0, 1709164800L },
        { "year-2000-is-leap", 2000, 2, 29, 0, 0, 0, 0, 951782400L },
        { "year-1900-is-not-leap", 1900, 3, 1, 0, 0, 0, 0, -2203891200L },
        { "int32-max", 2038, 1, 19, 3, 14, 7, 0, 2147483647L },
        { "after-int32-max", 2038, 1, 19, 3, 14, 8, 0, 2147483648L },
        { "int32-min", 1901, 12, 13, 20, 45, 52, 0, -2147483648L },
        { "year-99-is-not-1999", 99, 12, 31, 23, 59, 59, 0, -59011459201L },
        { "first-second-of-year-1", 1, 1, 1, 0, 0, 0, 0, -62135596800L },
        { "last-second-of-year-9999", 9999, 12, 31, 23, 59, 59, 0, 253402300799L },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void UnixTimestamp(string name, int year, int month, int day, int hour, int minute, int second, int offset, long want)
    {
        Assert.Equal(want, UnixTime.UnixTimestamp(year, month, day, hour, minute, second, offset));
        var back = DateTimeOffset.FromUnixTimeSeconds(want).ToOffset(TimeSpan.FromMinutes(offset));
        Assert.Equal(new DateTime(year, month, day, hour, minute, second), back.DateTime);
        Assert.NotNull(name);
    }

    [Fact]
    public void Now()
    {
        long seconds = UnixTime.NowUnixSeconds();
        long millis = UnixTime.NowUnixMillis();
        Assert.True(seconds >= 1_704_067_200L);
        long diff = millis / 1000 - seconds;
        Assert.InRange(diff, 0L, 1L);
    }
}
unix.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

/**
 * Returns the seconds since 1970-01-01T00:00:00Z of a local time with the given UTC offset.
 * Date.UTC is not used, because it reads the years 0 to 99 as 1900 to 1999.
 * @param {number} year
 * @param {number} month 1 to 12
 * @param {number} day
 * @param {number} hour
 * @param {number} minute
 * @param {number} second
 * @param {number} offsetMinutes positive east of Greenwich
 * @returns {number}
 */
export function unixTimestamp(year, month, day, hour, minute, second, offsetMinutes) {
  const date = new Date(0);
  date.setUTCFullYear(year, month - 1, day);
  date.setUTCHours(hour, minute - offsetMinutes, second, 0);
  return date.getTime() / 1000;
}

/** Returns the current Unix time in whole seconds, rounded toward the past. */
export function nowUnixSeconds() {
  return Math.floor(Date.now() / 1000);
}

/** Returns the current Unix time in milliseconds. */
export function nowUnixMillis() {
  return Date.now();
}
unix.test.js 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

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

import { nowUnixMillis, nowUnixSeconds, unixTimestamp } from "./unix.js";

const cases = [
  ["epoch", [1970, 1, 1, 0, 0, 0, 0], 0],
  ["billennium", [2001, 9, 9, 1, 46, 40, 0], 1000000000],
  ["negative-offset", [2024, 3, 10, 2, 0, 0, -300], 1710054000],
  ["positive-offset", [2024, 3, 10, 16, 0, 0, 540], 1710054000],
  ["one-second-before-epoch", [1969, 12, 31, 23, 59, 59, 0], -1],
  ["offset-moves-before-epoch", [1970, 1, 1, 0, 0, 0, 60], -3600],
  ["offset-moves-to-next-year", [2023, 12, 31, 19, 0, 0, -300], 1704067200],
  ["offset-of-45-minutes", [2024, 1, 1, 5, 45, 0, 345], 1704067200],
  ["offset-of-minus-9-30", [2023, 12, 31, 14, 30, 0, -570], 1704067200],
  ["offset-plus-14", [1970, 1, 1, 14, 0, 0, 840], 0],
  ["offset-minus-12", [1969, 12, 31, 12, 0, 0, -720], 0],
  ["leap-day", [2024, 2, 29, 0, 0, 0, 0], 1709164800],
  ["year-2000-is-leap", [2000, 2, 29, 0, 0, 0, 0], 951782400],
  ["year-1900-is-not-leap", [1900, 3, 1, 0, 0, 0, 0], -2203891200],
  ["int32-max", [2038, 1, 19, 3, 14, 7, 0], 2147483647],
  ["after-int32-max", [2038, 1, 19, 3, 14, 8, 0], 2147483648],
  ["int32-min", [1901, 12, 13, 20, 45, 52, 0], -2147483648],
  ["year-99-is-not-1999", [99, 12, 31, 23, 59, 59, 0], -59011459201],
  ["first-second-of-year-1", [1, 1, 1, 0, 0, 0, 0], -62135596800],
  ["last-second-of-year-9999", [9999, 12, 31, 23, 59, 59, 0], 253402300799],
];

for (const [name, fields, want] of cases) {
  test(name, () => {
    const [year, month, day, hour, minute, second, offset] = fields;
    assert.equal(unixTimestamp(year, month, day, hour, minute, second, offset), want);
  });
}

test("Date.UTC reads year 99 as 1999", () => {
  assert.equal(Date.UTC(99, 11, 31, 23, 59, 59) / 1000, 946684799);
  assert.equal(unixTimestamp(99, 12, 31, 23, 59, 59, 0), -59011459201);
});

test("back to a date", () => {
  assert.equal(new Date(1710054000 * 1000).toISOString(), "2024-03-10T07:00:00.000Z");
  assert.equal(new Date(-62135596800 * 1000).toISOString(), "0001-01-01T00:00:00.000Z");
});

test("now", () => {
  const seconds = nowUnixSeconds();
  const millis = nowUnixMillis();
  assert.ok(Number.isInteger(seconds) && seconds >= 1704067200);
  const diff = Math.floor(millis / 1000) - seconds;
  assert.ok(diff >= 0 && diff <= 1);
});
unix.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

/**
 * Returns the seconds since 1970-01-01T00:00:00Z of a local time with the given UTC offset.
 * Date.UTC is not used, because it reads the years 0 to 99 as 1900 to 1999.
 */
export function unixTimestamp(
  year: number,
  month: number,
  day: number,
  hour: number,
  minute: number,
  second: number,
  offsetMinutes: number,
): number {
  const date = new Date(0);
  date.setUTCFullYear(year, month - 1, day);
  date.setUTCHours(hour, minute - offsetMinutes, second, 0);
  return date.getTime() / 1000;
}

/** Returns the current Unix time in whole seconds, rounded toward the past. */
export function nowUnixSeconds(): number {
  return Math.floor(Date.now() / 1000);
}

/** Returns the current Unix time in milliseconds. */
export function nowUnixMillis(): number {
  return Date.now();
}
unix.test.ts 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

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

import { nowUnixMillis, nowUnixSeconds, unixTimestamp } from "./unix.ts";

const cases: [string, number[], number][] = [
  ["epoch", [1970, 1, 1, 0, 0, 0, 0], 0],
  ["billennium", [2001, 9, 9, 1, 46, 40, 0], 1000000000],
  ["negative-offset", [2024, 3, 10, 2, 0, 0, -300], 1710054000],
  ["positive-offset", [2024, 3, 10, 16, 0, 0, 540], 1710054000],
  ["one-second-before-epoch", [1969, 12, 31, 23, 59, 59, 0], -1],
  ["offset-moves-before-epoch", [1970, 1, 1, 0, 0, 0, 60], -3600],
  ["offset-moves-to-next-year", [2023, 12, 31, 19, 0, 0, -300], 1704067200],
  ["offset-of-45-minutes", [2024, 1, 1, 5, 45, 0, 345], 1704067200],
  ["offset-of-minus-9-30", [2023, 12, 31, 14, 30, 0, -570], 1704067200],
  ["offset-plus-14", [1970, 1, 1, 14, 0, 0, 840], 0],
  ["offset-minus-12", [1969, 12, 31, 12, 0, 0, -720], 0],
  ["leap-day", [2024, 2, 29, 0, 0, 0, 0], 1709164800],
  ["year-2000-is-leap", [2000, 2, 29, 0, 0, 0, 0], 951782400],
  ["year-1900-is-not-leap", [1900, 3, 1, 0, 0, 0, 0], -2203891200],
  ["int32-max", [2038, 1, 19, 3, 14, 7, 0], 2147483647],
  ["after-int32-max", [2038, 1, 19, 3, 14, 8, 0], 2147483648],
  ["int32-min", [1901, 12, 13, 20, 45, 52, 0], -2147483648],
  ["year-99-is-not-1999", [99, 12, 31, 23, 59, 59, 0], -59011459201],
  ["first-second-of-year-1", [1, 1, 1, 0, 0, 0, 0], -62135596800],
  ["last-second-of-year-9999", [9999, 12, 31, 23, 59, 59, 0], 253402300799],
];

for (const [name, fields, want] of cases) {
  test(name, () => {
    const [year, month, day, hour, minute, second, offset] = fields;
    assert.equal(unixTimestamp(year, month, day, hour, minute, second, offset), want);
  });
}

test("Date.UTC reads year 99 as 1999", () => {
  assert.equal(Date.UTC(99, 11, 31, 23, 59, 59) / 1000, 946684799);
  assert.equal(unixTimestamp(99, 12, 31, 23, 59, 59, 0), -59011459201);
});

test("back to a date", () => {
  assert.equal(new Date(1710054000 * 1000).toISOString(), "2024-03-10T07:00:00.000Z");
  assert.equal(new Date(-62135596800 * 1000).toISOString(), "0001-01-01T00:00:00.000Z");
});

test("now", () => {
  const seconds = nowUnixSeconds();
  const millis = nowUnixMillis();
  assert.ok(Number.isInteger(seconds) && seconds >= 1704067200);
  const diff = Math.floor(millis / 1000) - seconds;
  assert.ok(diff >= 0 && diff <= 1);
});
unix.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

package unix

import "time"

// UnixTimestamp returns the seconds since 1970-01-01T00:00:00Z of a local
// time with the given UTC offset in minutes.
func UnixTimestamp(year, month, day, hour, minute, second, offsetMinutes int) int64 {
	zone := time.FixedZone("", offsetMinutes*60)
	return time.Date(year, time.Month(month), day, hour, minute, second, 0, zone).Unix()
}

// NowUnixSeconds returns the current Unix time in whole seconds.
func NowUnixSeconds() int64 {
	return time.Now().Unix()
}

// NowUnixMillis returns the current Unix time in whole milliseconds.
func NowUnixMillis() int64 {
	return time.Now().UnixMilli()
}
unix_test.go 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

package unix

import (
	"testing"
	"time"
)

var cases = []struct {
	name                                              string
	year, month, day, hour, minute, second, offsetMin int
	want                                              int64
}{
	{"epoch", 1970, 1, 1, 0, 0, 0, 0, 0},
	{"billennium", 2001, 9, 9, 1, 46, 40, 0, 1000000000},
	{"negative-offset", 2024, 3, 10, 2, 0, 0, -300, 1710054000},
	{"positive-offset", 2024, 3, 10, 16, 0, 0, 540, 1710054000},
	{"one-second-before-epoch", 1969, 12, 31, 23, 59, 59, 0, -1},
	{"offset-moves-before-epoch", 1970, 1, 1, 0, 0, 0, 60, -3600},
	{"offset-moves-to-next-year", 2023, 12, 31, 19, 0, 0, -300, 1704067200},
	{"offset-of-45-minutes", 2024, 1, 1, 5, 45, 0, 345, 1704067200},
	{"offset-of-minus-9-30", 2023, 12, 31, 14, 30, 0, -570, 1704067200},
	{"offset-plus-14", 1970, 1, 1, 14, 0, 0, 840, 0},
	{"offset-minus-12", 1969, 12, 31, 12, 0, 0, -720, 0},
	{"leap-day", 2024, 2, 29, 0, 0, 0, 0, 1709164800},
	{"year-2000-is-leap", 2000, 2, 29, 0, 0, 0, 0, 951782400},
	{"year-1900-is-not-leap", 1900, 3, 1, 0, 0, 0, 0, -2203891200},
	{"int32-max", 2038, 1, 19, 3, 14, 7, 0, 2147483647},
	{"after-int32-max", 2038, 1, 19, 3, 14, 8, 0, 2147483648},
	{"int32-min", 1901, 12, 13, 20, 45, 52, 0, -2147483648},
	{"year-99-is-not-1999", 99, 12, 31, 23, 59, 59, 0, -59011459201},
	{"first-second-of-year-1", 1, 1, 1, 0, 0, 0, 0, -62135596800},
	{"last-second-of-year-9999", 9999, 12, 31, 23, 59, 59, 0, 253402300799},
}

func TestUnixTimestamp(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := UnixTimestamp(c.year, c.month, c.day, c.hour, c.minute, c.second, c.offsetMin)
			if got != c.want {
				t.Fatalf("got %d, want %d", got, c.want)
			}
			back := time.Unix(c.want, 0).In(time.FixedZone("", c.offsetMin*60))
			if back.Year() != c.year || int(back.Month()) != c.month || back.Day() != c.day ||
				back.Hour() != c.hour || back.Minute() != c.minute || back.Second() != c.second {
				t.Fatalf("back to a date: got %v", back)
			}
		})
	}
}

func TestNow(t *testing.T) {
	seconds := NowUnixSeconds()
	millis := NowUnixMillis()
	if seconds < 1704067200 {
		t.Fatalf("seconds %d is before 2024", seconds)
	}
	if diff := millis/1000 - seconds; diff < 0 || diff > 1 {
		t.Fatalf("millis %d and seconds %d do not agree", millis, seconds)
	}
}
unix.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

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

/// Returns the number of days from 1970-01-01 to a date in the proleptic
/// Gregorian calendar. This is the days_from_civil algorithm of Howard Hinnant.
pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let y = if month <= 2 { year - 1 } else { year };
    let era = y.div_euclid(400);
    let yoe = y - era * 400; // 0 to 399
    let mp = (month + 9) % 12; // March is 0
    let doy = (153 * mp + 2) / 5 + day - 1; // 0 to 365
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // 0 to 146096
    era * 146_097 + doe - 719_468
}

/// Returns the seconds since 1970-01-01T00:00:00Z of a local time with the
/// given UTC offset in minutes.
pub fn unix_timestamp(
    year: i64,
    month: i64,
    day: i64,
    hour: i64,
    minute: i64,
    second: i64,
    offset_minutes: i64,
) -> i64 {
    days_from_civil(year, month, day) * 86_400 + hour * 3_600 + (minute - offset_minutes) * 60 + second
}

/// Returns the current Unix time in whole milliseconds, rounded toward the
/// past. A system clock set before 1970 gives a negative value.
pub fn now_unix_millis() -> i64 {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(after) => after.as_millis() as i64,
        Err(before) => -(before.duration().as_nanos().div_ceil(1_000_000) as i64),
    }
}

/// Returns the current Unix time in whole seconds, rounded toward the past.
pub fn now_unix_seconds() -> i64 {
    now_unix_millis().div_euclid(1_000)
}
tests/unix_test.rs 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-a-unix-timestamp/.

use algo_get_a_unix_timestamp::{days_from_civil, now_unix_millis, now_unix_seconds, unix_timestamp};

#[allow(clippy::type_complexity)]
const CASES: &[(&str, i64, i64, i64, i64, i64, i64, i64, i64)] = &[
    ("epoch", 1970, 1, 1, 0, 0, 0, 0, 0),
    ("billennium", 2001, 9, 9, 1, 46, 40, 0, 1000000000),
    ("negative-offset", 2024, 3, 10, 2, 0, 0, -300, 1710054000),
    ("positive-offset", 2024, 3, 10, 16, 0, 0, 540, 1710054000),
    ("one-second-before-epoch", 1969, 12, 31, 23, 59, 59, 0, -1),
    ("offset-moves-before-epoch", 1970, 1, 1, 0, 0, 0, 60, -3600),
    ("offset-moves-to-next-year", 2023, 12, 31, 19, 0, 0, -300, 1704067200),
    ("offset-of-45-minutes", 2024, 1, 1, 5, 45, 0, 345, 1704067200),
    ("offset-of-minus-9-30", 2023, 12, 31, 14, 30, 0, -570, 1704067200),
    ("offset-plus-14", 1970, 1, 1, 14, 0, 0, 840, 0),
    ("offset-minus-12", 1969, 12, 31, 12, 0, 0, -720, 0),
    ("leap-day", 2024, 2, 29, 0, 0, 0, 0, 1709164800),
    ("year-2000-is-leap", 2000, 2, 29, 0, 0, 0, 0, 951782400),
    ("year-1900-is-not-leap", 1900, 3, 1, 0, 0, 0, 0, -2203891200),
    ("int32-max", 2038, 1, 19, 3, 14, 7, 0, 2147483647),
    ("after-int32-max", 2038, 1, 19, 3, 14, 8, 0, 2147483648),
    ("int32-min", 1901, 12, 13, 20, 45, 52, 0, -2147483648),
    ("year-99-is-not-1999", 99, 12, 31, 23, 59, 59, 0, -59011459201),
    ("first-second-of-year-1", 1, 1, 1, 0, 0, 0, 0, -62135596800),
    ("last-second-of-year-9999", 9999, 12, 31, 23, 59, 59, 0, 253402300799),
];

#[test]
fn cases() {
    for &(name, year, month, day, hour, minute, second, offset, want) in CASES {
        assert_eq!(unix_timestamp(year, month, day, hour, minute, second, offset), want, "{name}");
    }
}

#[test]
fn days_from_civil_known_dates() {
    assert_eq!(days_from_civil(1970, 1, 1), 0);
    assert_eq!(days_from_civil(1969, 12, 31), -1);
    assert_eq!(days_from_civil(2000, 3, 1) - days_from_civil(2000, 2, 28), 2);
    assert_eq!(days_from_civil(1900, 3, 1) - days_from_civil(1900, 2, 28), 1);
}

#[test]
fn now() {
    let seconds = now_unix_seconds();
    let millis = now_unix_millis();
    assert!(seconds >= 1_704_067_200);
    let diff = millis.div_euclid(1_000) - seconds;
    assert!((0..=1).contains(&diff));
}
unix.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-unix-timestamp/.

# unix_timestamp YEAR MONTH DAY HOUR MINUTE SECOND OFFSET_MINUTES
# Prints the seconds since 1970-01-01T00:00:00Z of a local time with the given
# UTC offset. It needs GNU date, which reads a date with an offset after -d.
unix_timestamp() {
  local year=$1 month=$2 day=$3 hour=$4 minute=$5 second=$6 offset=$7
  local sign=+
  if (( offset < 0 )); then
    sign=-
    offset=$(( -offset ))
  fi
  local text
  printf -v text '%04d-%02d-%02dT%02d:%02d:%02d%s%02d:%02d' \
    "$year" "$month" "$day" "$hour" "$minute" "$second" "$sign" $(( offset / 60 )) $(( offset % 60 ))
  date -u -d "$text" +%s
}

# now_unix_seconds prints the current Unix time in whole seconds.
now_unix_seconds() {
  printf '%s\n' "$EPOCHSECONDS"
}

# now_unix_millis prints the current Unix time in whole milliseconds.
now_unix_millis() {
  local micros=${EPOCHREALTIME//[!0-9]/}
  printf '%s\n' $(( micros / 1000 ))
}
test_unix.bats 45 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-a-unix-timestamp/.

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

@test "epoch" { run unix_timestamp 1970 1 1 0 0 0 0; [ "$status" -eq 0 ]; [ "$output" = "0" ]; }
@test "billennium" { run unix_timestamp 2001 9 9 1 46 40 0; [ "$status" -eq 0 ]; [ "$output" = "1000000000" ]; }
@test "negative-offset" { run unix_timestamp 2024 3 10 2 0 0 -300; [ "$status" -eq 0 ]; [ "$output" = "1710054000" ]; }
@test "positive-offset" { run unix_timestamp 2024 3 10 16 0 0 540; [ "$status" -eq 0 ]; [ "$output" = "1710054000" ]; }
@test "one-second-before-epoch" { run unix_timestamp 1969 12 31 23 59 59 0; [ "$status" -eq 0 ]; [ "$output" = "-1" ]; }
@test "offset-moves-before-epoch" { run unix_timestamp 1970 1 1 0 0 0 60; [ "$status" -eq 0 ]; [ "$output" = "-3600" ]; }
@test "offset-moves-to-next-year" { run unix_timestamp 2023 12 31 19 0 0 -300; [ "$status" -eq 0 ]; [ "$output" = "1704067200" ]; }
@test "offset-of-45-minutes" { run unix_timestamp 2024 1 1 5 45 0 345; [ "$status" -eq 0 ]; [ "$output" = "1704067200" ]; }
@test "offset-of-minus-9-30" { run unix_timestamp 2023 12 31 14 30 0 -570; [ "$status" -eq 0 ]; [ "$output" = "1704067200" ]; }
@test "offset-plus-14" { run unix_timestamp 1970 1 1 14 0 0 840; [ "$status" -eq 0 ]; [ "$output" = "0" ]; }
@test "offset-minus-12" { run unix_timestamp 1969 12 31 12 0 0 -720; [ "$status" -eq 0 ]; [ "$output" = "0" ]; }
@test "leap-day" { run unix_timestamp 2024 2 29 0 0 0 0; [ "$status" -eq 0 ]; [ "$output" = "1709164800" ]; }
@test "year-2000-is-leap" { run unix_timestamp 2000 2 29 0 0 0 0; [ "$status" -eq 0 ]; [ "$output" = "951782400" ]; }
@test "year-1900-is-not-leap" { run unix_timestamp 1900 3 1 0 0 0 0; [ "$status" -eq 0 ]; [ "$output" = "-2203891200" ]; }
@test "int32-max" { run unix_timestamp 2038 1 19 3 14 7 0; [ "$status" -eq 0 ]; [ "$output" = "2147483647" ]; }
@test "after-int32-max" { run unix_timestamp 2038 1 19 3 14 8 0; [ "$status" -eq 0 ]; [ "$output" = "2147483648" ]; }
@test "int32-min" { run unix_timestamp 1901 12 13 20 45 52 0; [ "$status" -eq 0 ]; [ "$output" = "-2147483648" ]; }
@test "year-99-is-not-1999" { run unix_timestamp 99 12 31 23 59 59 0; [ "$status" -eq 0 ]; [ "$output" = "-59011459201" ]; }
@test "first-second-of-year-1" { run unix_timestamp 1 1 1 0 0 0 0; [ "$status" -eq 0 ]; [ "$output" = "-62135596800" ]; }
@test "last-second-of-year-9999" { run unix_timestamp 9999 12 31 23 59 59 0; [ "$status" -eq 0 ]; [ "$output" = "253402300799" ]; }

@test "back to a date" {
  run date -u -d @1710054000 +%Y-%m-%dT%H:%M:%S
  [ "$output" = "2024-03-10T07:00:00" ]
  run date -u -d @-62135596800 +%Y-%m-%dT%H:%M:%S
  [ "$output" = "0001-01-01T00:00:00" ]
}

@test "now" {
  seconds=$(now_unix_seconds)
  millis=$(now_unix_millis)
  [[ $seconds =~ ^[0-9]+$ ]]
  [[ $millis =~ ^[0-9]+$ ]]
  (( seconds >= 1704067200 ))
  diff=$(( millis / 1000 - seconds ))
  (( diff >= 0 && diff <= 1 ))
}

References

  1. The Open Group Base Specifications Issue 8, General Concepts, 4.19 Seconds Since the Epoch
  2. The Open Group Base Specifications Issue 8, time, DESCRIPTION
  3. The Open Group Base Specifications Issue 8, mktime, DESCRIPTION
  4. The Python Standard Library, time, time.time, time.time_ns, time.mktime
  5. The Python Standard Library, datetime, datetime.timestamp, datetime.fromtimestamp
  6. The Python Standard Library, calendar, calendar.timegm
  7. MDN Web Docs, Date, The epoch, timestamps, and invalid date
  8. MDN Web Docs, Date.UTC(), Parameters, year
  9. MDN Web Docs, Date.now(), Return value; Reduced time precision
  10. Java SE 25 API, java.time.Instant, getEpochSecond(); toEpochMilli(); ofEpochSecond(long); ofEpochMilli(long)
  11. Java SE 25 API, java.time.OffsetDateTime, toEpochSecond()
  12. Java SE 25 API, java.lang.System, currentTimeMillis()
  13. .NET API reference, DateTimeOffset.ToUnixTimeSeconds, Returns; Remarks
  14. .NET API reference, DateTimeOffset.FromUnixTimeSeconds, Exceptions; Remarks
  15. Go standard library, time, func Unix; func UnixMilli; func (Time) Unix; func (Time) UnixMilli; func FixedZone
  16. The Rust Standard Library, std::time::SystemTime, duration_since; UNIX_EPOCH; Examples
  17. cppreference.com, timegm, the description of the function; Return value
  18. cppreference.com, std::chrono::system_clock, the description of the class
  19. cppreference.com, std::chrono::year_month_day, the description of the class; operator sys_days
  20. Bash Reference Manual, 5.2 Bash Variables: EPOCHSECONDS, EPOCHREALTIME
  21. Linux manual page, date(1), FORMAT: %s; EXAMPLES: convert seconds since the Epoch

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