filemtime
filemtime(string $filename): int|false
Returns the file's last modification time (mtime) as Unix epoch seconds, or false on failure; cached per path, so clearstatcache before re-reading.
C 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 fills in the XXXXXX part
int fd = mkstemp(path);
close(fd);
// set mtime explicitly to a fixed epoch (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);
// format in UTC: gmtime + strftime ignores the local timezone
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
#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 fills in the XXXXXX part
int fd = mkstemp(path);
close(fd);
// set mtime explicitly to a fixed epoch (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";
// format in UTC: gmtime ignores the local timezone
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
using System.IO;
var path = Path.GetTempFileName();
// set mtime explicitly to a fixed epoch (2009-02-13 23:31:30 UTC)
File.SetLastWriteTimeUtc(path, DateTimeOffset.FromUnixTimeSeconds(1234567890).UtcDateTime);
// GetLastWriteTimeUtc returns DateTime; convert back to epoch seconds
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
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)
// set mtime explicitly to a fixed epoch (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())
// format in UTC: .UTC() ignores the local timezone
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
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");
// set mtime explicitly to a fixed epoch (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));
// format in UTC: ZoneOffset.UTC ignores the local timezone
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
const fs = require("fs");
const os = require("os");
const dir = fs.mkdtempSync(os.tmpdir() + "/fmt_");
const path = `${dir}/demo.dat`;
fs.writeFileSync(path, "x"); // create the file first
// set mtime explicitly to a fixed epoch (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; // a Date built from the epoch value
console.log(Math.floor(mtime.getTime() / 1000));
// format in UTC: toISOString is always 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
$file = tempnam(sys_get_temp_dir(), 'fmt_');
touch($file, 1234567890); // set mtime explicitly (2009-02-13 23:31:30 UTC)
echo filemtime($file), "\n";
// gmdate formats in UTC, ignoring the local timezone
echo gmdate('Y-m-d H:i:s', filemtime($file)), " UTC\n";
// failure reports false, not an exception
var_dump(filemtime('/nonexistent_fmt_demo'));
unlink($file);
1234567890 2009-02-13 23:31:30 UTC bool(false)
Python v3.15.2
import os
import tempfile
from datetime import datetime, timezone
fd, path = tempfile.mkstemp(prefix="fmt_")
os.close(fd)
# set mtime explicitly to a fixed epoch (2009-02-13 23:31:30 UTC)
os.utime(path, (1234567890, 1234567890)) # (atime, mtime)
mtime = int(os.stat(path).st_mtime)
print(mtime)
# format in UTC: fromtimestamp(ts, timezone.utc) ignores the local timezone
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
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 has no set-mtime API, so read a freshly created file instead:
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();
// print deterministic properties rather than the raw (run-dependent) value
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
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"); // create the file first
// set mtime explicitly to a fixed epoch (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; // a Date built from the epoch value
console.log(Math.floor(mtime.getTime() / 1000));
// format in UTC: toISOString is always 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
Language differences
C: the st_mtime field of stat (seconds); set mtime with utimes(path, times) (sys/time.h, first element atime, second mtime); format with gmtime + strftime (localtime would apply the local timezone).
C++: same as C — std::filesystem::last_write_time behaves differently between C++17/20 due to the file_clock vs system_clock epoch gap, so POSIX utimes is the steadier way to set a fixed value.
C#: File.SetLastWriteTimeUtc / File.GetLastWriteTimeUtc — always use the Utc-suffixed variants; the unsuffixed ones apply the local timezone; DateTimeOffset.ToUnixTimeSeconds() converts to epoch seconds.
Go: set with os.Chtimes(path, atime, mtime); read via FileInfo.ModTime(); format by applying .UTC() before Format — the 2006-01-02 15:04:05 template is Go's reference-time notation.
Java: NIO Files.setLastModifiedTime(path, FileTime.fromMillis(...)) / Files.getLastModifiedTime; millisecond precision, so multiply epoch seconds by 1000; format via Instant.atOffset(ZoneOffset.UTC).
JavaScript: fs.utimesSync(path, atime, mtime) to set (accepts Date objects or seconds); statSync().mtime returns a Date and toISOString() always prints UTC.
PHP: filemtime returns Unix seconds; touch($file, $time) sets mtime explicitly; results are cached per path — but touch()/file_put_contents() refresh that path's cache on their own write (in-script write-then-read always sees the fresh value), so clearstatcache() is really for re-reading after an external process changed the file; format with gmdate (date applies the timezone); failure returns false.
Python: os.utime(path, (atime, mtime)) to set; os.stat().st_mtime (float seconds, int() truncates); format via datetime.fromtimestamp(ts, timezone.utc).
Rust: std::fs::metadata(path).modified() reads mtime (a SystemTime); std has no API to set mtime (cross-platform setting needs a third-party crate like filetime), so the snippet reads a fresh file and asserts properties (10-digit epoch seconds + freshness) instead of printing a run-dependent value.
TypeScript: same as JS.