filemtime

filemtime(string $filename): int|false

返回文件的最后修改时间(mtime,Unix 时间戳秒),失败返回 false;结果按路径缓存,重读前需 clearstatcache。

C C23

C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

int main(void) {
    char path[] = "/tmp/fmt_XXXXXX"; // mkstemp 会填入 XXXXXX 部分
    int fd = mkstemp(path);
    close(fd);

    // 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
    struct timeval times[2] = {{1234567890, 0}, {1234567890, 0}};
    utimes(path, times);

    struct stat st;
    stat(path, &st);
    printf("%lld\n", (long long)st.st_mtime);
    // 按 UTC 格式化:gmtime + strftime 不受本地时区影响
    char buf[32];
    strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", gmtime(&st.st_mtime));
    printf("%s UTC\n", buf);

    unlink(path);
    return 0;
}
输出
1234567890
2009-02-13 23:31:30 UTC

C++ C++26

C++26
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>

int main() {
    char path[] = "/tmp/fmt_cpp_XXXXXX"; // mkstemp 会填入 XXXXXX 部分
    int fd = mkstemp(path);
    close(fd);

    // 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
    timeval times[2] = {{1234567890, 0}, {1234567890, 0}};
    utimes(path, times);

    struct stat st;
    stat(path, &st);
    std::cout << static_cast<long long>(st.st_mtime) << "\n";
    // 按 UTC 格式化:gmtime 不受本地时区影响
    std::tm tmv = *std::gmtime(&st.st_mtime);
    std::cout << std::put_time(&tmv, "%Y-%m-%d %H:%M:%S") << " UTC\n";

    unlink(path);
    return 0;
}
输出
1234567890
2009-02-13 23:31:30 UTC

C# v11.0.100

v11.0.100
using System.IO;

var path = Path.GetTempFileName();
// 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
File.SetLastWriteTimeUtc(path, DateTimeOffset.FromUnixTimeSeconds(1234567890).UtcDateTime);

// GetLastWriteTimeUtc 返回 DateTime;转回 Unix 秒
var mtime = ((DateTimeOffset)File.GetLastWriteTimeUtc(path)).ToUnixTimeSeconds();
Console.WriteLine(mtime);
Console.WriteLine(File.GetLastWriteTimeUtc(path).ToString("yyyy-MM-dd HH:mm:ss") + " UTC");

File.Delete(path);
输出
1234567890
2009-02-13 23:31:30 UTC

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	path := fmt.Sprintf("%s/fmt_go_%d", os.TempDir(), os.Getpid())
	os.WriteFile(path, []byte("x"), 0644)

	// 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
	fixed := time.Unix(1234567890, 0)
	os.Chtimes(path, fixed, fixed)

	fi, _ := os.Stat(path)
	fmt.Println(fi.ModTime().Unix())
	// 按 UTC 格式化:.UTC() 不受本地时区影响
	fmt.Println(fi.ModTime().UTC().Format("2006-01-02 15:04:05") + " UTC")

	os.Remove(path)
}
输出
1234567890
2009-02-13 23:31:30 UTC

Java v27.0.1

v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        Path path = Files.createTempFile("fmt", ".tmp");
        // 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
        Files.setLastModifiedTime(path, FileTime.fromMillis(1234567890000L));

        FileTime mtime = Files.getLastModifiedTime(path);
        System.out.println(mtime.to(TimeUnit.SECONDS));
        // 按 UTC 格式化:ZoneOffset.UTC 不受本地时区影响
        String formatted = Instant.ofEpochMilli(mtime.toMillis())
                .atOffset(ZoneOffset.UTC)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(formatted + " UTC");

        Files.delete(path);
    }
}
输出
1234567890
2009-02-13 23:31:30 UTC

JavaScript v26.13.1

v26.13.1
const fs = require("fs");
const os = require("os");
const dir = fs.mkdtempSync(os.tmpdir() + "/fmt_");
const path = `${dir}/demo.dat`;
fs.writeFileSync(path, "x"); // 先创建文件

// 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
const fixed = new Date(1234567890 * 1000);
fs.utimesSync(path, fixed, fixed); // (atime, mtime)

const mtime = fs.statSync(path).mtime; // 由 epoch 值构建的 Date
console.log(Math.floor(mtime.getTime() / 1000));
// 按 UTC 格式化:toISOString 恒为 UTC
console.log(mtime.toISOString().slice(0, 19).replace("T", " ") + " UTC");

fs.unlinkSync(path);
fs.rmSync(dir, { recursive: true, force: true });
输出
1234567890
2009-02-13 23:31:30 UTC

PHP v8.6.0

v8.6.0
$file = tempnam(sys_get_temp_dir(), 'fmt_');
touch($file, 1234567890); // 显式设定 mtime(2009-02-13 23:31:30 UTC)
echo filemtime($file), "\n";
// gmdate 按 UTC 格式化,不受本地时区影响
echo gmdate('Y-m-d H:i:s', filemtime($file)), " UTC\n";
// 失败报告 false,而非异常
var_dump(filemtime('/nonexistent_fmt_demo'));
unlink($file);
输出
1234567890
2009-02-13 23:31:30 UTC
bool(false)

Python v3.15.2

v3.15.2
import os
import tempfile
from datetime import datetime, timezone

fd, path = tempfile.mkstemp(prefix="fmt_")
os.close(fd)

# 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
os.utime(path, (1234567890, 1234567890))  # (atime, mtime)

mtime = int(os.stat(path).st_mtime)
print(mtime)
# 按 UTC 格式化:fromtimestamp(ts, timezone.utc) 不受本地时区影响
print(datetime.fromtimestamp(mtime, timezone.utc).strftime("%Y-%m-%d %H:%M:%S"), "UTC")

os.unlink(path)
输出
1234567890
2009-02-13 23:31:30 UTC

Rust v1.99.1

v1.99.1
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let path = std::env::temp_dir().join(format!("fmt_rs_{}", std::process::id()));
    fs::write(&path, b"x").unwrap();

    // std 没有「设置 mtime」的 API,改为读取刚创建的文件:
    let mtime = fs::metadata(&path)
        .unwrap()
        .modified()
        .unwrap()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
    // 打印确定性属性,而不是随运行变化的原始值
    println!("epoch seconds: {} digits", mtime.to_string().len());
    println!("fresh (age < 60s): {}", now - mtime < 60);

    fs::remove_file(&path).unwrap();
}
输出
epoch seconds: 10 digits
fresh (age < 60s): true

TypeScript v26.13.1

v26.13.1
import * as fs from "fs";
import * as os from "os";

const dir = fs.mkdtempSync(`${os.tmpdir()}/fmt_`);
const path = `${dir}/demo.dat`;
fs.writeFileSync(path, "x"); // 先创建文件

// 显式把 mtime 设为固定时间点(2009-02-13 23:31:30 UTC)
const fixed = new Date(1234567890 * 1000);
fs.utimesSync(path, fixed, fixed); // (atime, mtime)

const mtime = fs.statSync(path).mtime; // 由 epoch 值构建的 Date
console.log(Math.floor(mtime.getTime() / 1000));
// 按 UTC 格式化:toISOString 恒为 UTC
console.log(mtime.toISOString().slice(0, 19).replace("T", " ") + " UTC");

fs.unlinkSync(path);
fs.rmSync(dir, { recursive: true, force: true });
输出
1234567890
2009-02-13 23:31:30 UTC

语言差异说明

C:stat 的 st_mtime 字段(秒);设置 mtime 用 utimes(path, times)(sys/time.h,第一个元素 atime、第二个 mtime);格式化用 gmtime + strftime(localtime 会受时区影响)。

C++:同 C(std::filesystem 的 last_write_time 因 file_clock 与 system_clock 的 epoch 差异在 C++17/20 间行为不同,设固定值不如直接用 POSIX utimes 稳)。

C#:File.SetLastWriteTimeUtc / File.GetLastWriteTimeUtc——务必用 Utc 后缀版本,无后缀版走本地时区;DateTimeOffset.ToUnixTimeSeconds() 与 epoch 秒互转。

Go:os.Chtimes(path, atime, mtime) 设置;FileInfo.ModTime() 读取;格式化先 .UTC() 再 Format,模板 2006-01-02 15:04:05 是 Go 特有的参考时间写法。

Java:NIO Files.setLastModifiedTime(path, FileTime.fromMillis(...)) / Files.getLastModifiedTime;毫秒精度,epoch 秒 ×1000;格式化用 Instant.atOffset(ZoneOffset.UTC)。

JavaScript:fs.utimesSync(path, atime, mtime) 设置(Date 对象或秒数均可);statSync().mtime 返回 Date,toISOString() 恒输出 UTC。

PHP:filemtime 返回 Unix 秒;touch($file, $time) 可显式设定 mtime;结果按路径缓存——但 touch()/file_put_contents() 自身会同步刷新该路径的缓存(脚本内自改自读总是新值),clearstatcache() 真正用于外部进程改文件后的重读;格式化用 gmdate(date 受时区影响);失败返回 false。

Python:os.utime(path, (atime, mtime)) 设置;os.stat().st_mtime(浮点秒,int() 取整);格式化用 datetime.fromtimestamp(ts, timezone.utc)。

Rust:std::fs::metadata(path).modified() 读 mtime(SystemTime);std 没有设置 mtime 的 API(跨平台设值要 filetime 等第三方 crate),所以示例改为读新建文件并断言属性(10 位 epoch 秒 + 新鲜度),避免输出随运行时间漂移。

TypeScript:同 JS。