In Java, Files.setLastModifiedTime(path, time) sets the last-modified time of a file or folder. Build the value with FileTime.fromMillis(ms), FileTime.from(n, TimeUnit), or (Java 8) FileTime.from(instant).
It is how you "touch" a file, restore a timestamp after editing, or create repeatable test data. The file system may round the value to its precision.
A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.setLastModifiedTime(...), after import java.nio.file.Files;. You never create a Files object.
Run with java SetLastModifiedTimeUnits. The time is a fixed value set by the program, so the output is the same on Windows, macOS, and Linux.
From seconds: 2009-02-13T23:31:30Z
From Instant: 2020-01-01T00:00:00Z
How It Works
Unix seconds.FileTime.from(1234567890, SECONDS) is the famous Unix time 1234567890, reached on 13 February 2009.
Readable dates.Instant.parse (Java 8) accepts an ISO-8601 string, which is easier to read than a number.
Last call wins. Each call replaces the previous time, so the second read shows 2020.
Example 3 — Do Milliseconds Survive?
Set a time with 123 milliseconds and check what the file system kept.
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.concurrent.TimeUnit;
public class SetLastModifiedTimePrecision {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("demo");
Path file = Files.write(dir.resolve("precise.txt"), new byte[0]);
Files.setLastModifiedTime(file, FileTime.fromMillis(1_000_000_000_123L));
FileTime back = Files.getLastModifiedTime(file);
System.out.println("Whole seconds kept: " + (back.to(TimeUnit.SECONDS) == 1_000_000_000L));
System.out.println("Milliseconds kept: " + (back.toMillis() == 1_000_000_000_123L));
Files.delete(file);
Files.delete(dir);
}
}
Output
Run with java SetLastModifiedTimePrecision. Typical output on NTFS (Windows), ext4 (Linux), and APFS (macOS); the second line can be false on file systems with coarser precision.
Whole seconds kept: true
Milliseconds kept: true
How It Works
A fractional time. 1,000,000,000,123 ms is 01:46:40.123 on 9 September 2001.
Seconds are safe. Every common file system keeps the whole seconds.
Fractions depend on the disk. NTFS, ext4, and APFS keep milliseconds, so this prints true; FAT, HFS+, and some older JDKs on macOS keep whole seconds only and would print false.