Programming Search⌘K

Taskintro

Get the modification time of a file

Also called file modification time, last modified time, mtime, last write time, file timestamp.

Get the time of the last change to the data of a file as Unix time in whole seconds, and know how it differs from the change, access and creation times.

Task

Return the modification time of the file at path: the time of the last change to its data. Give it as Unix time, the count of whole seconds since 1970-01-01T00:00:00Z. A time with a part of a second gives the second before it (the floor), also for a time before 1970. So -1.5 seconds gives -2, not -1. Report an error when no file is at path. A directory has a modification time too, so a directory is not an error.

The Linux manual says what changes this time: "It is changed by file modifications, for example, by mknod(2) , truncate(2) , utime(2) , and write(2) (of more than zero bytes). Moreover, the mtime timestamp of a directory is changed by the creation or deletion of files in that directory. The mtime timestamp is not changed for changes in owner, group, hard link count, or mode."

A file has more times than one. POSIX gives three in struct stat: "struct timespec st_mtim Last data modification timestamp. struct timespec st_ctim Last file status change timestamp." The third, st_atim, is the time of the last access. Some systems also keep a creation time. The pitfalls show why each is not the modification time.

SQL, regular expressions, HTML and CSS do not apply, because they do not get information about files.

Solutions

Each language gets the time from the status of the file, and each call follows a symbolic link, so a link gives the time of its target. The time is kept in a more exact unit than a second, so each solution must convert it to seconds with a floor.

  • Python. os.stat(path).st_mtime_ns // 1_000_000_000. st_mtime_ns is the "Time of most recent content modification expressed in nanoseconds as an integer." The // operator gives the floor, also for a negative count. st_mtime is a float, and a float does not keep all the nanoseconds of a time in this century. See the pitfalls.
  • JavaScript and TypeScript (Node.js). (await fsPromises.stat(path, { bigint: true })).mtimeNs. mtimeNs is "Only present when bigint: true is passed into the method that generates the object." The division of two bigint values rounds toward zero, so the code subtracts 1 when the remainder is negative.
  • Java. Files.getLastModifiedTime(path).toInstant().getEpochSecond(). toInstant "creates an Instant that represents the same point on the time-line as this FileTime", and getEpochSecond gives the floor.
  • C#. File.GetLastWriteTimeUtc(path), and then new DateTimeOffset(time).ToUnixTimeSeconds(). This call gives no error for a missing file: "If the file described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC)." So the code throws FileNotFoundException first. For a symbolic link, the call gives the time of the link itself. The native test shows this on macOS. So the code gets the final target with ResolveLinkTarget(returnFinalTarget: true) first, and reads LastWriteTimeUtc from it.
  • Go. os.Stat(path), and then fi.ModTime().Unix(). Unix gives the floor. The result is an int64.
  • Rust. fs::metadata(path)?.modified()?. It "Returns the last modification time listed in this metadata. The returned value corresponds to the mtime field of stat on Unix platforms and the ftLastWriteTime field on Windows platforms." A SystemTime has no count of seconds. duration_since(UNIX_EPOCH) gives one, but it gives an error for a time before 1970. The error has the distance in the other direction, so the code makes it negative and takes the floor.
  • C. POSIX stat(path, &st), and then st.st_mtime, which is the seconds part of st_mtim. The nanoseconds part is never negative, so the seconds part is the floor. ISO C has no call that gets the time of a file.
  • C++. std::filesystem::last_write_time(path, ec). It "Returns the time of the last modification of p , determined as if by accessing the member st_mtime of the POSIX stat (symlinks are followed)." The result is a file_clock time, and for file_clock, "Its epoch is unspecified." So the code converts it with file_clock::to_sys, and then uses std::chrono::floor<seconds>. A duration_cast rounds toward zero.
  • Bash. POSIX has no utility that prints the time of a file in seconds. date -r "$path" +%s works in GNU date ("-r, --reference=FILE display the last modification time of FILE") and in the date of macOS, but it is not POSIX. The date of macOS reads a number as a count of seconds when no file has that name, so the function returns status 1 for a missing file first. The native tests check this with a missing file named 1709296496.

On Windows, a file time is a FILETIME, which has "a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC)." That is the reason for the year 1601 in C#.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each test makes the file in a new temporary directory, sets its modification time to mtime_ns, and checks the result. The tests set the time with the call of each language: os.utime, utimes, Files.setLastModifiedTime, File.SetLastWriteTimeUtc, os.Chtimes, File::set_modified, utimensat, last_write_time, and touch -d.

  • whole-second and sub-second: 2024-03-01T12:34:56Z, and the same time and a half second. Both give 1709296496.
  • epoch: 0.
  • before-1970: one day before 1970 gives -86400. before-1970-sub-second: -1.5 seconds gives -2. A conversion that rounds toward zero gives -1.
  • after-2038: 2100-01-01T00:00:00Z gives 4102444800. That is more than a signed 32-bit integer can hold.
  • directory: a directory gives its time.
  • name-with-spaces: my notes.txt. A shell solution must quote the name.
  • Errors, in cases/errors.jsonl: a missing file gives not-found.

The native tests also check that a symbolic link gives the time of its target, and that a write to a file sets its time to the present time.

Pitfalls

  • The change time is not the creation time. ctime is the time of the last change to the status of the file, and a change to the mode is a change of status. Python says that st_ctime is the "Time of most recent metadata change expressed in seconds", and the Linux manual says that it "is changed by writing or by setting inode information (i.e., owner, group, link count, mode, etc.)." A chmod changes it, but it does not change the modification time:

This code runs but gives a wrong answer on purpose.

import os
import tempfile
import time

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "a.txt")
    with open(path, "w") as f:
        f.write("alpha\n")
    made = os.stat(path).st_ctime_ns
    time.sleep(0.05)
    os.chmod(path, 0o600)  # no change to the data
    st = os.stat(path)
    print("ctime changed:", st.st_ctime_ns > made)
    print("mtime changed:", st.st_mtime_ns > made)
Output
ctime changed: True
mtime changed: False

On Windows, st_ctime is deprecated, and the documentation says: "Use st_birthtime for the file creation time." The creation time is not always present. st_birthtime "is not always available, and may raise AttributeError". On Linux, it comes from statx, and the Linux manual says that it "is not currently supported by most Linux filesystems." Rust gives it as Metadata::created, Node as stats.birthtime, and Java as creationTime().

  • The access time is not exact. The access time changes on a read, but a system can stop the update to save writes: "Some filesystem types allow mounting in such a way that file and/or directory accesses do not cause an update of the atime timestamp." Do not use it to find the last time a program read a file.

  • A float loses nanoseconds. A floating-point number does not keep all the digits of a time in this century in nanoseconds. So st_mtime in Python does not keep the exact time:

This code runs but gives a wrong answer on purpose.

import os
import tempfile

with tempfile.TemporaryDirectory() as dir:
    path = os.path.join(dir, "a.txt")
    open(path, "w").close()
    ns = 1709296496_123456789
    os.utime(path, ns=(ns, ns))
    st = os.stat(path)
    print("st_mtime_ns:   ", st.st_mtime_ns)
    print("from st_mtime: ", int(st.st_mtime * 1_000_000_000))
Output
st_mtime_ns:    1709296496123456789
from st_mtime:  1709296496123456768

To compare two times exactly, for example to see if a file changed since a build, use the integer forms: st_mtime_ns, mtimeNs, or the timespec of stat.

  • The resolution of the file system. The time that a program sets is not always the time that it gets back. Go says: "The underlying filesystem may truncate or round the values to a less precise time unit." The Linux manual says: "Nanosecond timestamps are not supported in ext2, ext3, and Reiserfs." So two writes in the same second can give the same time, and a check that one file is newer than another must allow equal times.

  • Local time and UTC. Unix time has no time zone. A conversion to a date and an hour needs one, and the default is the local time zone of the computer:

import os
import time
from datetime import datetime, timezone

os.environ["TZ"] = "Asia/Ho_Chi_Minh"
time.tzset()
mtime = 1709296496
print("local:", datetime.fromtimestamp(mtime))
print("UTC:  ", datetime.fromtimestamp(mtime, tz=timezone.utc))
Output
local: 2024-03-01 19:34:56
UTC:   2024-03-01 12:34:56+00:00

Keep and compare times as Unix time, or as dates with a time zone. The same is true for touch -d: the time zone "is either empty, signifying local time, or the letter 'Z' , signifying UTC."

  • A time before 1970 that Node does not set. utimes in Node takes numbers of seconds, but it uses the present time for a negative number. The documentation does not say this. A Date works:

This code runs but gives a wrong answer on purpose.

const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mtime-"));
const file = path.join(dir, "a.txt");
fs.writeFileSync(file, "alpha\n");
fs.utimesSync(file, -86400, -86400); // 1969-12-31 as a number of seconds
console.log("year:", fs.statSync(file).mtime.getUTCFullYear() === 1969 ? 1969 : "not 1969");
fs.utimesSync(file, new Date(-86400000), new Date(-86400000));
console.log("year:", fs.statSync(file).mtime.getUTCFullYear());
fs.rmSync(dir, { recursive: true });
Output
year: not 1969
year: 1969

For touch, POSIX says: "If the resulting time precedes the Epoch, the behavior is implementation-defined."

  • A missing file with a time. In C#, File.GetLastWriteTimeUtc gives 1601-01-01 for a missing file, with no error. A program that sorts files by time puts the missing file first. Check that the file exists, or use FileInfo and its Exists property.

Code

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

file_mtime.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import os


def file_mtime(path: str | os.PathLike) -> int:
    """Returns the modification time of the file at path, in whole seconds
    since 1970-01-01T00:00:00Z.

    os.stat follows a symbolic link. st_mtime_ns is an exact integer, so the
    floor division gives the correct second, also before 1970. A missing
    file raises FileNotFoundError.
    """
    return os.stat(path).st_mtime_ns // 1_000_000_000
test_file_mtime.py 56 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import os
import time
from pathlib import Path

import pytest

from file_mtime import file_mtime

# name: (path, mtime_ns, result)
CASES = {
    "whole-second": ("a.txt", 1709296496_000000000, 1709296496),
    "sub-second": ("a.txt", 1709296496_500000000, 1709296496),
    "epoch": ("a.txt", 0, 0),
    "before-1970": ("a.txt", -86400_000000000, -86400),
    "before-1970-sub-second": ("a.txt", -1_500000000, -2),
    "after-2038": ("a.txt", 4102444800_000000000, 4102444800),
    "directory": ("dir", 1709296496_000000000, 1709296496),
    "name-with-spaces": ("my notes.txt", 1709296496_000000000, 1709296496),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    rel, ns, want = CASES[name]
    path = tmp_path / rel
    if rel == "dir":
        path.mkdir()
    else:
        path.write_text("alpha\n")
    os.utime(path, ns=(ns, ns))
    assert file_mtime(path) == want


def test_errors(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        file_mtime(tmp_path / "a.txt")


def test_symbolic_link(tmp_path: Path) -> None:
    (tmp_path / "a.txt").write_text("alpha\n")
    os.utime(tmp_path / "a.txt", ns=(0, 1709296496_000000000))
    os.symlink("a.txt", tmp_path / "link")
    assert file_mtime(tmp_path / "link") == 1709296496


def test_write_sets_the_present_time(tmp_path: Path) -> None:
    path = tmp_path / "a.txt"
    path.write_text("alpha\n")
    os.utime(path, ns=(0, 0))
    before = int(time.time()) - 1
    with open(path, "a") as f:
        f.write("beta\n")
    assert file_mtime(path) >= before
file_mtime.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

#include "file_mtime.hpp"

#include <chrono>

namespace fs = std::filesystem;

std::int64_t file_mtime(const fs::path& path, std::error_code& ec) {
    fs::file_time_type t = fs::last_write_time(path, ec);
    if (ec) return 0;
    // The epoch of file_clock is not given by the standard, so the code
    // converts the time to system_clock, which counts from 1970. floor, not
    // duration_cast, gives the second before a time before 1970.
    auto sys = std::chrono::file_clock::to_sys(t);
    return std::chrono::floor<std::chrono::seconds>(sys.time_since_epoch()).count();
}
file_mtime.hpp 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

#pragma once

#include <cstdint>
#include <filesystem>
#include <system_error>

// Returns the modification time of the file at path, in whole seconds since
// 1970-01-01T00:00:00Z, with std::filesystem::last_write_time. It follows a
// symbolic link. On an error it sets ec, for example
// std::errc::no_such_file_or_directory, and returns 0.
std::int64_t file_mtime(const std::filesystem::path& path, std::error_code& ec);
test_file_mtime.cpp 91 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

#include <chrono>
#include <cstdint>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <system_error>

#include "file_mtime.hpp"

namespace fs = std::filesystem;
namespace chrono = std::chrono;

namespace {

const fs::path dir = "file_mtime_tree";
int failures = 0;

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

void fresh() {
    fs::remove_all(dir);
    fs::create_directories(dir);
}

void set_mtime(const fs::path& p, std::int64_t ns) {
    chrono::sys_time<chrono::nanoseconds> t{chrono::nanoseconds{ns}};
    fs::last_write_time(p, chrono::file_clock::from_sys(t));
}

void run_case(const char* name, const char* rel, std::int64_t ns, std::int64_t want) {
    fresh();
    fs::path p = dir / rel;
    if (rel[0] == 'd') {
        fs::create_directory(p);
    } else {
        std::ofstream(p) << "alpha\n";
    }
    set_mtime(p, ns);
    std::error_code ec;
    expect(file_mtime(p, ec) == want && !ec, name);
}

void test_errors() {
    fresh();
    std::error_code ec;
    file_mtime(dir / "a.txt", ec);
    expect(ec == std::errc::no_such_file_or_directory, "missing");
}

void test_link_and_write() {
    fresh();
    std::error_code ec;
    std::ofstream(dir / "a.txt") << "alpha\n";
    set_mtime(dir / "a.txt", 1709296496000000000);
    fs::create_symlink("a.txt", dir / "link");
    expect(file_mtime(dir / "link", ec) == 1709296496 && !ec, "link");
    set_mtime(dir / "a.txt", 0);
    auto now = chrono::floor<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count();
    std::ofstream(dir / "a.txt", std::ios::app) << "beta\n";
    expect(file_mtime(dir / "a.txt", ec) >= now - 1 && !ec, "present time");
}

}  // namespace

int main() {
    run_case("whole-second", "a.txt", 1709296496000000000, 1709296496);
    run_case("sub-second", "a.txt", 1709296496500000000, 1709296496);
    run_case("epoch", "a.txt", 0, 0);
    run_case("before-1970", "a.txt", -86400000000000, -86400);
    run_case("before-1970-sub-second", "a.txt", -1500000000, -2);
    run_case("after-2038", "a.txt", 4102444800000000000, 4102444800);
    run_case("directory", "dir", 1709296496000000000, 1709296496);
    run_case("name-with-spaces", "my notes.txt", 1709296496000000000, 1709296496);
    test_errors();
    test_link_and_write();
    fs::remove_all(dir);
    if (failures != 0) {
        std::fprintf(stderr, "%d failures\n", failures);
        return 1;
    }
    std::puts("ok");
    return 0;
}
FileMtime.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

final class FileMtime {
  private FileMtime() {}

  /**
   * Returns the modification time of the file at path, in whole seconds since
   * 1970-01-01T00:00:00Z. getLastModifiedTime follows a symbolic link. Instant.getEpochSecond gives
   * the floor, also before 1970. A missing file gives NoSuchFileException.
   */
  static long mtime(Path path) throws IOException {
    return Files.getLastModifiedTime(path).toInstant().getEpochSecond();
  }
}
FileMtimeTest.java 89 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileTime;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class FileMtimeTest {
  @TempDir Path dir;

  @ParameterizedTest(name = "{0}")
  @CsvSource({
    "whole-second, a.txt, 1709296496000000000, 1709296496",
    "sub-second, a.txt, 1709296496500000000, 1709296496",
    "epoch, a.txt, 0, 0",
    "before-1970, a.txt, -86400000000000, -86400",
    "before-1970-sub-second, a.txt, -1500000000, -2",
    "after-2038, a.txt, 4102444800000000000, 4102444800",
    "directory, dir, 1709296496000000000, 1709296496",
    "name-with-spaces, my notes.txt, 1709296496000000000, 1709296496",
  })
  void cases(String name, String rel, long ns, long want) throws IOException {
    Path path = dir.resolve(rel);
    if (rel.equals("dir")) {
      Files.createDirectory(path);
    } else {
      Files.writeString(path, "alpha\n");
    }
    setTime(path, ns);
    assertEquals(want, FileMtime.mtime(path), name);
  }

  // On Linux, the JDK 25 that the tests ran on set a time such as -1.5 s to 0, but it
  // read the time back correctly. So when the time that it reads back is not the time
  // that the test asked for, the test sets the time with GNU touch, and it skips the case
  // when touch cannot set the time either.
  private static void setTime(Path path, long ns) throws IOException {
    Files.setLastModifiedTime(path, FileTime.from(ns, TimeUnit.NANOSECONDS));
    if (Files.getLastModifiedTime(path).to(TimeUnit.NANOSECONDS) == ns) {
      return;
    }
    String stamp = "@" + java.math.BigDecimal.valueOf(ns, 9).toPlainString();
    int status;
    try {
      status = new ProcessBuilder("touch", "-d", stamp, path.toString()).inheritIO().start().waitFor();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IOException(e);
    }
    assumeTrue(status == 0 && Files.getLastModifiedTime(path).to(TimeUnit.NANOSECONDS) == ns,
        "this system cannot set the time " + stamp);
  }

  @Test
  void errors() {
    assertThrows(NoSuchFileException.class, () -> FileMtime.mtime(dir.resolve("a.txt")));
  }

  @Test
  void symbolicLink() throws IOException {
    Files.writeString(dir.resolve("a.txt"), "alpha\n");
    Files.setLastModifiedTime(dir.resolve("a.txt"), FileTime.from(1709296496, TimeUnit.SECONDS));
    Files.createSymbolicLink(dir.resolve("link"), Path.of("a.txt"));
    assertEquals(1709296496, FileMtime.mtime(dir.resolve("link")));
  }

  @Test
  void writeSetsThePresentTime() throws IOException {
    Path path = dir.resolve("a.txt");
    Files.writeString(path, "alpha\n");
    Files.setLastModifiedTime(path, FileTime.fromMillis(0));
    long before = System.currentTimeMillis() / 1000 - 1;
    Files.writeString(path, "beta\n", StandardOpenOption.APPEND);
    assertTrue(FileMtime.mtime(path) >= before);
  }
}
file_mtime.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

#define _POSIX_C_SOURCE 200809L

#include "file_mtime.h"

#include <sys/stat.h>

int file_mtime(const char *path, time_t *mtime) {
    struct stat st;
    if (stat(path, &st) != 0) return -1;
    // st_mtime is the tv_sec part of the time. It is the floor, because the
    // tv_nsec part is never negative, also before 1970.
    *mtime = st.st_mtime;
    return 0;
}
file_mtime.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

#ifndef FILE_MTIME_H
#define FILE_MTIME_H

#include <time.h>

// file_mtime stores the modification time of the file at path in *mtime, in
// whole seconds since 1970-01-01T00:00:00Z. stat follows a symbolic link. It
// returns 0, or -1 with errno, for example ENOENT for a missing file.
int file_mtime(const char *path, time_t *mtime);

#endif
test_file_mtime.c 102 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

#define _POSIX_C_SOURCE 200809L

#include "file_mtime.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>

static const char *dir = "file_mtime_tree";
static int failures = 0;

static char *at(char *buf, const char *name) {
    snprintf(buf, 256, "%s/%s", dir, name);
    return buf;
}

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

static void fresh(void) {
    if (system("rm -rf file_mtime_tree") != 0 || mkdir(dir, 0755) != 0) exit(2);
}

static void make(const char *name) {
    char p[256];
    FILE *f = fopen(at(p, name), "w");
    if (f == NULL || fputs("alpha\n", f) < 0 || fclose(f) != 0) exit(2);
}

// set_mtime sets the modification time of path to sec + nsec / 1e9 seconds.
static void set_mtime(const char *path, time_t sec, long nsec) {
    struct timespec ts[2] = {{0, UTIME_OMIT}, {sec, nsec}};
    if (utimensat(AT_FDCWD, path, ts, 0) != 0) exit(2);
}

static void run_case(const char *name, const char *rel, time_t sec, long nsec, time_t want) {
    char p[256];
    time_t got = 12345;
    fresh();
    if (rel[0] == 'd') {
        if (mkdir(at(p, rel), 0755) != 0) exit(2);
    } else {
        make(rel);
    }
    set_mtime(at(p, rel), sec, nsec);
    expect(file_mtime(p, &got) == 0 && got == want, name);
}

static void test_errors(void) {
    char p[256];
    time_t got;
    fresh();
    errno = 0;
    expect(file_mtime(at(p, "a.txt"), &got) == -1 && errno == ENOENT, "missing");
}

static void test_link_and_write(void) {
    char p[256], q[256];
    time_t got = 0;
    fresh();
    make("a.txt");
    set_mtime(at(p, "a.txt"), 1709296496, 0);
    expect(symlink("a.txt", at(q, "link")) == 0, "symlink");
    expect(file_mtime(q, &got) == 0 && got == 1709296496, "link");

    set_mtime(p, 0, 0);
    time_t before = time(NULL) - 1;
    int f = open(p, O_WRONLY | O_APPEND);
    expect(f >= 0 && write(f, "beta\n", 5) == 5 && close(f) == 0, "write");
    expect(file_mtime(p, &got) == 0 && got >= before, "present time");
}

int main(void) {
    // A time of -1.5 s is -2 s and 500000000 ns: tv_nsec is never negative.
    run_case("whole-second", "a.txt", 1709296496, 0, 1709296496);
    run_case("sub-second", "a.txt", 1709296496, 500000000, 1709296496);
    run_case("epoch", "a.txt", 0, 0, 0);
    run_case("before-1970", "a.txt", -86400, 0, -86400);
    run_case("before-1970-sub-second", "a.txt", -2, 500000000, -2);
    run_case("after-2038", "a.txt", (time_t)4102444800, 0, (time_t)4102444800);
    run_case("directory", "dir", 1709296496, 0, 1709296496);
    run_case("name-with-spaces", "my notes.txt", 1709296496, 0, 1709296496);
    test_errors();
    test_link_and_write();
    if (system("rm -rf file_mtime_tree") != 0) failures++;
    if (failures != 0) {
        fprintf(stderr, "%d failures\n", failures);
        return 1;
    }
    puts("ok");
    return 0;
}
FileMtime.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

public static class FileMtime
{
    /// <summary>
    /// Returns the modification time of the file or directory at path, in whole
    /// seconds since 1970-01-01T00:00:00Z. File.GetLastWriteTimeUtc gives no
    /// error for a missing file: it gives 1601-01-01T00:00:00Z. So the code
    /// throws FileNotFoundException first. ToUnixTimeSeconds gives the floor,
    /// also before 1970. For a symbolic link, File.GetLastWriteTimeUtc gives the
    /// time of the link itself, so the code gets the final target first.
    /// </summary>
    public static long Mtime(string path)
    {
        if (!File.Exists(path) && !Directory.Exists(path))
        {
            throw new FileNotFoundException($"No such file: '{path}'", path);
        }
        FileSystemInfo info = Directory.Exists(path) ? new DirectoryInfo(path) : new FileInfo(path);
        if (info.LinkTarget != null)
        {
            info = info.ResolveLinkTarget(returnFinalTarget: true) ?? info;
        }
        return new DateTimeOffset(info.LastWriteTimeUtc).ToUnixTimeSeconds();
    }
}
FileMtimeTests.cs 76 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

using Xunit;

public sealed class FileMtimeTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("file-mtime-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private static DateTime FromNs(long ns) => DateTime.UnixEpoch.AddTicks(ns / 100);

    // name, path, mtime_ns, result
    public static TheoryData<string, string, long, long> Cases => new()
    {
        { "whole-second", "a.txt", 1709296496000000000, 1709296496 },
        { "sub-second", "a.txt", 1709296496500000000, 1709296496 },
        { "epoch", "a.txt", 0, 0 },
        { "before-1970", "a.txt", -86400000000000, -86400 },
        { "before-1970-sub-second", "a.txt", -1500000000, -2 },
        { "after-2038", "a.txt", 4102444800000000000, 4102444800 },
        { "directory", "dir", 1709296496000000000, 1709296496 },
        { "name-with-spaces", "my notes.txt", 1709296496000000000, 1709296496 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Case(string name, string rel, long ns, long want)
    {
        string path = Path.Combine(dir, rel);
        if (rel == "dir")
        {
            Directory.CreateDirectory(path);
            Directory.SetLastWriteTimeUtc(path, FromNs(ns));
        }
        else
        {
            File.WriteAllText(path, "alpha\n");
            File.SetLastWriteTimeUtc(path, FromNs(ns));
        }
        Assert.True(want == FileMtime.Mtime(path), name);
    }

    [Fact]
    public void Errors()
    {
        string path = Path.Combine(dir, "a.txt");
        Assert.Throws<FileNotFoundException>(() => FileMtime.Mtime(path));
        // File.GetLastWriteTimeUtc alone gives a time, not an error.
        Assert.Equal(new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc), File.GetLastWriteTimeUtc(path));
    }

    [Fact]
    public void SymbolicLink()
    {
        string target = Path.Combine(dir, "a.txt");
        File.WriteAllText(target, "alpha\n");
        File.SetLastWriteTimeUtc(target, FromNs(1709296496000000000));
        File.CreateSymbolicLink(Path.Combine(dir, "link"), "a.txt");
        Assert.Equal(1709296496, FileMtime.Mtime(Path.Combine(dir, "link")));
        // File.GetLastWriteTimeUtc alone gives the time of the link.
        Assert.NotEqual(FromNs(1709296496000000000), File.GetLastWriteTimeUtc(Path.Combine(dir, "link")));
    }

    [Fact]
    public void WriteSetsThePresentTime()
    {
        string path = Path.Combine(dir, "a.txt");
        File.WriteAllText(path, "alpha\n");
        File.SetLastWriteTimeUtc(path, DateTime.UnixEpoch);
        long before = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 1;
        File.AppendAllText(path, "beta\n");
        Assert.True(FileMtime.Mtime(path) >= before);
    }
}
fileMtime.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import { stat } from "node:fs/promises";

const NS_PER_SECOND = 1_000_000_000n;

/**
 * Returns the modification time of the file at path, in whole seconds since
 * 1970-01-01T00:00:00Z. stat follows a symbolic link. With bigint: true, the
 * time is an exact count of nanoseconds (mtimeNs). The division of two
 * bigints rounds toward zero, so the code subtracts 1 for a time before 1970
 * with a part of a second. A missing file gives an error with the code ENOENT.
 */
export async function fileMtime(path) {
  const ns = (await stat(path, { bigint: true })).mtimeNs;
  let s = ns / NS_PER_SECOND;
  if (ns % NS_PER_SECOND < 0n) s -= 1n;
  return Number(s);
}
fileMtime.test.js 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { appendFile, mkdir, mkdtemp, rm, symlink, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileMtime } from "./fileMtime.js";

async function withDir(fn) {
  const dir = await mkdtemp(join(tmpdir(), "file-mtime-"));
  try {
    await fn(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

// name, path, mtime in milliseconds, result. utimes takes a Date: it uses the
// present time for a negative number of seconds.
const cases = [
  ["whole-second", "a.txt", 1709296496000, 1709296496],
  ["sub-second", "a.txt", 1709296496500, 1709296496],
  ["epoch", "a.txt", 0, 0],
  ["before-1970", "a.txt", -86400000, -86400],
  ["before-1970-sub-second", "a.txt", -1500, -2],
  ["after-2038", "a.txt", 4102444800000, 4102444800],
  ["directory", "dir", 1709296496000, 1709296496],
  ["name-with-spaces", "my notes.txt", 1709296496000, 1709296496],
];

for (const [name, rel, mtime, want] of cases) {
  test(name, () =>
    withDir(async (dir) => {
      const path = join(dir, rel);
      if (rel === "dir") await mkdir(path);
      else await writeFile(path, "alpha\n");
      await utimes(path, new Date(mtime), new Date(mtime));
      assert.equal(await fileMtime(path), want);
    }),
  );
}

test("errors", () =>
  withDir(async (dir) => {
    await assert.rejects(fileMtime(join(dir, "a.txt")), { code: "ENOENT" });
  }));

test("symbolic link", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await utimes(join(dir, "a.txt"), 0, 1709296496);
    await symlink("a.txt", join(dir, "link"));
    assert.equal(await fileMtime(join(dir, "link")), 1709296496);
  }));

test("write sets the present time", () =>
  withDir(async (dir) => {
    const path = join(dir, "a.txt");
    await writeFile(path, "alpha\n");
    await utimes(path, 0, 0);
    const before = Math.floor(Date.now() / 1000) - 1;
    await appendFile(path, "beta\n");
    assert.ok((await fileMtime(path)) >= before);
  }));
fileMtime.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import { stat } from "node:fs/promises";

const NS_PER_SECOND = 1_000_000_000n;

/**
 * Returns the modification time of the file at path, in whole seconds since
 * 1970-01-01T00:00:00Z. stat follows a symbolic link. With bigint: true, the
 * time is an exact count of nanoseconds (mtimeNs). The division of two
 * bigints rounds toward zero, so the code subtracts 1 for a time before 1970
 * with a part of a second. A missing file gives an error with the code ENOENT.
 */
export async function fileMtime(path: string): Promise<number> {
  const ns = (await stat(path, { bigint: true })).mtimeNs;
  let s = ns / NS_PER_SECOND;
  if (ns % NS_PER_SECOND < 0n) s -= 1n;
  return Number(s);
}
fileMtime.test.ts 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

import { test } from "node:test";
import assert from "node:assert/strict";
import { appendFile, mkdir, mkdtemp, rm, symlink, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileMtime } from "./fileMtime.ts";

async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
  const dir = await mkdtemp(join(tmpdir(), "file-mtime-"));
  try {
    await fn(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

// name, path, mtime in milliseconds, result. utimes takes a Date: it uses the
// present time for a negative number of seconds.
const cases: [string, string, number, number][] = [
  ["whole-second", "a.txt", 1709296496000, 1709296496],
  ["sub-second", "a.txt", 1709296496500, 1709296496],
  ["epoch", "a.txt", 0, 0],
  ["before-1970", "a.txt", -86400000, -86400],
  ["before-1970-sub-second", "a.txt", -1500, -2],
  ["after-2038", "a.txt", 4102444800000, 4102444800],
  ["directory", "dir", 1709296496000, 1709296496],
  ["name-with-spaces", "my notes.txt", 1709296496000, 1709296496],
];

for (const [name, rel, mtime, want] of cases) {
  test(name, () =>
    withDir(async (dir) => {
      const path = join(dir, rel);
      if (rel === "dir") await mkdir(path);
      else await writeFile(path, "alpha\n");
      await utimes(path, new Date(mtime), new Date(mtime));
      assert.equal(await fileMtime(path), want);
    }),
  );
}

test("errors", () =>
  withDir(async (dir) => {
    await assert.rejects(fileMtime(join(dir, "a.txt")), { code: "ENOENT" });
  }));

test("symbolic link", () =>
  withDir(async (dir) => {
    await writeFile(join(dir, "a.txt"), "alpha\n");
    await utimes(join(dir, "a.txt"), 0, 1709296496);
    await symlink("a.txt", join(dir, "link"));
    assert.equal(await fileMtime(join(dir, "link")), 1709296496);
  }));

test("write sets the present time", () =>
  withDir(async (dir) => {
    const path = join(dir, "a.txt");
    await writeFile(path, "alpha\n");
    await utimes(path, 0, 0);
    const before = Math.floor(Date.now() / 1000) - 1;
    await appendFile(path, "beta\n");
    assert.ok((await fileMtime(path)) >= before);
  }));
file_mtime.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

// Package filemtime gets the modification time of a file.
package filemtime

import "os"

// FileMtime returns the modification time of the file at path, in whole
// seconds since 1970-01-01T00:00:00Z. os.Stat follows a symbolic link.
// time.Time.Unix gives the floor, also before 1970. A missing file gives a
// *fs.PathError with fs.ErrNotExist.
func FileMtime(path string) (int64, error) {
	fi, err := os.Stat(path)
	if err != nil {
		return 0, err
	}
	return fi.ModTime().Unix(), nil
}
file_mtime_test.go 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

package filemtime

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"testing"
	"time"
)

func must(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatal(err)
	}
}

func TestCases(t *testing.T) {
	for _, c := range []struct {
		name, path string
		ns, want   int64
	}{
		{"whole-second", "a.txt", 1709296496000000000, 1709296496},
		{"sub-second", "a.txt", 1709296496500000000, 1709296496},
		{"epoch", "a.txt", 0, 0},
		{"before-1970", "a.txt", -86400000000000, -86400},
		{"before-1970-sub-second", "a.txt", -1500000000, -2},
		{"after-2038", "a.txt", 4102444800000000000, 4102444800},
		{"directory", "dir", 1709296496000000000, 1709296496},
		{"name-with-spaces", "my notes.txt", 1709296496000000000, 1709296496},
	} {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(t.TempDir(), c.path)
			if c.path == "dir" {
				must(t, os.Mkdir(path, 0o755))
			} else {
				must(t, os.WriteFile(path, []byte("alpha\n"), 0o644))
			}
			tm := time.Unix(0, c.ns)
			must(t, os.Chtimes(path, tm, tm))
			if got, err := FileMtime(path); err != nil || got != c.want {
				t.Fatalf("FileMtime = %d, %v; want %d", got, err, c.want)
			}
		})
	}
}

func TestErrors(t *testing.T) {
	if _, err := FileMtime(filepath.Join(t.TempDir(), "a.txt")); !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("missing: %v", err)
	}
}

func TestSymbolicLink(t *testing.T) {
	dir := t.TempDir()
	must(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("alpha\n"), 0o644))
	must(t, os.Chtimes(filepath.Join(dir, "a.txt"), time.Unix(0, 0), time.Unix(1709296496, 0)))
	must(t, os.Symlink("a.txt", filepath.Join(dir, "link")))
	if got, err := FileMtime(filepath.Join(dir, "link")); err != nil || got != 1709296496 {
		t.Errorf("link: %d, %v", got, err)
	}
}

func TestWriteSetsThePresentTime(t *testing.T) {
	path := filepath.Join(t.TempDir(), "a.txt")
	must(t, os.WriteFile(path, []byte("alpha\n"), 0o644))
	must(t, os.Chtimes(path, time.Unix(0, 0), time.Unix(0, 0)))
	before := time.Now().Unix() - 1
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0)
	must(t, err)
	_, err = f.WriteString("beta\n")
	must(t, err)
	must(t, f.Close())
	if got, err := FileMtime(path); err != nil || got < before {
		t.Errorf("after write: %d, %v; want %d or more", got, err, before)
	}
}
file_mtime.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

use std::fs;
use std::io;
use std::path::Path;
use std::time::UNIX_EPOCH;

/// Returns the modification time of the file at `path`, in whole seconds
/// since 1970-01-01T00:00:00Z. `fs::metadata` follows a symbolic link.
/// `duration_since` gives an error for a time before 1970, with the
/// distance in the other direction, so the code makes that distance negative
/// and takes the floor. A missing file gives `ErrorKind::NotFound`.
pub fn file_mtime(path: &Path) -> io::Result<i64> {
    let t = fs::metadata(path)?.modified()?;
    Ok(match t.duration_since(UNIX_EPOCH) {
        Ok(d) => d.as_secs() as i64,
        Err(e) => {
            let d = e.duration();
            -(d.as_secs() as i64) - i64::from(d.subsec_nanos() > 0)
        }
    })
}
tests/file_mtime_test.rs 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

use std::fs::{self, File, OpenOptions};
use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use algo_get_the_modification_time_of_a_file::file_mtime;

/// Returns a new, empty directory for one test.
fn new_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("file-mtime-{}-{name}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

/// Sets the modification time of path to ns nanoseconds since 1970.
fn set_mtime(path: &Path, ns: i64) {
    let d = Duration::from_nanos(ns.unsigned_abs());
    let t = if ns >= 0 { UNIX_EPOCH + d } else { UNIX_EPOCH - d };
    File::open(path).unwrap().set_modified(t).unwrap();
}

#[test]
fn cases() {
    for (name, rel, ns, want) in [
        ("whole-second", "a.txt", 1709296496000000000, 1709296496),
        ("sub-second", "a.txt", 1709296496500000000, 1709296496),
        ("epoch", "a.txt", 0, 0),
        ("before-1970", "a.txt", -86400000000000, -86400),
        ("before-1970-sub-second", "a.txt", -1500000000, -2),
        ("after-2038", "a.txt", 4102444800000000000, 4102444800),
        ("directory", "dir", 1709296496000000000, 1709296496),
        ("name-with-spaces", "my notes.txt", 1709296496000000000, 1709296496),
    ] {
        let dir = new_dir(name);
        let path = dir.join(rel);
        if rel == "dir" {
            fs::create_dir(&path).unwrap();
        } else {
            fs::write(&path, "alpha\n").unwrap();
        }
        set_mtime(&path, ns);
        assert_eq!(file_mtime(&path).unwrap(), want, "{name}");
        fs::remove_dir_all(&dir).unwrap();
    }
}

#[test]
fn errors() {
    let dir = new_dir("errors");
    assert_eq!(file_mtime(&dir.join("a.txt")).unwrap_err().kind(), ErrorKind::NotFound);
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn symbolic_link() {
    let dir = new_dir("link");
    fs::write(dir.join("a.txt"), "alpha\n").unwrap();
    set_mtime(&dir.join("a.txt"), 1709296496000000000);
    std::os::unix::fs::symlink("a.txt", dir.join("link")).unwrap();
    assert_eq!(file_mtime(&dir.join("link")).unwrap(), 1709296496);
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn write_sets_the_present_time() {
    let dir = new_dir("write");
    let path = dir.join("a.txt");
    fs::write(&path, "alpha\n").unwrap();
    set_mtime(&path, 0);
    let before = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64 - 1;
    OpenOptions::new().append(true).open(&path).unwrap().write_all(b"beta\n").unwrap();
    assert!(file_mtime(&path).unwrap() >= before);
    fs::remove_dir_all(&dir).unwrap();
}
file_mtime.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

# file_mtime PATH
# Prints the modification time of the file at PATH, in whole seconds since
# 1970-01-01T00:00:00Z. POSIX has no utility that prints this time in
# seconds. date -r FILE does it in GNU date and in the date of macOS and the
# BSDs, but it is not POSIX. The date of macOS reads a number as a count of
# seconds when no file has that name, so the function returns status 1 for a
# missing file first. date -r follows a symbolic link.
file_mtime() {
  if [[ ! -e $1 ]]; then
    printf 'file_mtime: %s: no such file\n' "$1" >&2
    return 1
  fi
  date -r "$1" +%s
}
test_file_mtime.bats 75 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-modification-time-of-a-file/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/file_mtime.sh"
  dir=$BATS_TEST_TMPDIR
}

# touch -d takes a UTC time with a part of a second, as POSIX gives it.
@test "whole-second" {
  printf 'alpha\n' >"$dir/a.txt"
  touch -d 2024-03-01T12:34:56Z "$dir/a.txt"
  [ "$(file_mtime "$dir/a.txt")" = 1709296496 ]
}

@test "sub-second" {
  printf 'alpha\n' >"$dir/a.txt"
  touch -d 2024-03-01T12:34:56.5Z "$dir/a.txt"
  [ "$(file_mtime "$dir/a.txt")" = 1709296496 ]
}

@test "epoch" {
  printf 'alpha\n' >"$dir/a.txt"
  touch -d 1970-01-01T00:00:00Z "$dir/a.txt"
  [ "$(file_mtime "$dir/a.txt")" = 0 ]
}

@test "before-1970" {
  printf 'alpha\n' >"$dir/a.txt"
  touch -d 1969-12-31T00:00:00Z "$dir/a.txt"
  [ "$(file_mtime "$dir/a.txt")" = -86400 ]
}

@test "before-1970-sub-second" {
  printf 'alpha\n' >"$dir/a.txt"
  touch -d 1969-12-31T23:59:58.5Z "$dir/a.txt"
  [ "$(file_mtime "$dir/a.txt")" = -2 ]
}

@test "after-2038" {
  printf 'alpha\n' >"$dir/a.txt"
  touch -d 2100-01-01T00:00:00Z "$dir/a.txt"
  [ "$(file_mtime "$dir/a.txt")" = 4102444800 ]
}

@test "directory" {
  mkdir "$dir/dir"
  touch -d 2024-03-01T12:34:56Z "$dir/dir"
  [ "$(file_mtime "$dir/dir")" = 1709296496 ]
}

@test "name-with-spaces" {
  printf 'alpha\n' >"$dir/my notes.txt"
  touch -d 2024-03-01T12:34:56Z "$dir/my notes.txt"
  [ "$(file_mtime "$dir/my notes.txt")" = 1709296496 ]
}

@test "missing" {
  run -1 file_mtime "$dir/a.txt"
}

@test "missing name that is a number" {
  cd "$dir"
  run -1 file_mtime 1709296496
}

@test "symbolic link" {
  printf 'alpha\n' >"$dir/a.txt"
  touch -d 2024-03-01T12:34:56Z "$dir/a.txt"
  ln -s a.txt "$dir/link"
  [ "$(file_mtime "$dir/link")" = 1709296496 ]
}

References

  1. The Python Standard Library, os, Miscellaneous operating system interfaces, stat_result.st_mtime, st_mtime_ns, st_ctime, st_birthtime
  2. Node.js documentation, File system, stats.mtimeNs, stats.birthtime, fsPromises.utimes(path, atime, mtime)
  3. Java SE 25 API, BasicFileAttributes, lastModifiedTime(), creationTime()
  4. Java SE 25 API, FileTime, toInstant()
  5. .NET API reference, File.GetLastWriteTimeUtc Method, Remarks
  6. Go standard library, package os, func Stat, func Chtimes
  7. The Rust Standard Library, std::fs::Metadata, modified, created
  8. The Rust Standard Library, std::time::SystemTime, duration_since
  9. The Open Group Base Specifications Issue 8 (POSIX.1-2024), sys/stat.h, DESCRIPTION (st_atim, st_mtim, st_ctim)
  10. The Open Group Base Specifications Issue 8 (POSIX.1-2024), futimens, utimensat, DESCRIPTION
  11. The Open Group Base Specifications Issue 8 (POSIX.1-2024), touch, DESCRIPTION, OPTIONS (-d date_time), EXAMPLES
  12. Linux manual page, inode(7), File timestamps
  13. Linux manual page, date(1), -r, --reference
  14. cppreference, std::filesystem::last_write_time, Description
  15. cppreference, std::chrono::file_clock, Description
  16. Windows API reference, FILETIME structure (minwinbase.h), Description

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