我想获取我的计算机时区的最后修改日期(与我在 Windows 文件资源管理器中看到的相同)
System.out.println(myFile.lastModified()); // I get UTC
最佳答案
Returns: A long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs
所以需要将其转换为日期,如果您使用的是Java 8+,可以使用java.time API 像这样:
LocalDateTime date = LocalDateTime.ofInstant(
Instant.ofEpochMilli(myFile.lastModified()), ZoneId.systemDefault()
);
System.out.println(date);//example result : 2018-06-06T15:05:19.113
<小时/>
如果你想要更精确,你可以使用:
File myFile = new File("pathname");
Long timeMs = myFile.lastModified();
if (timeMs != 0) {
LocalDateTime date = LocalDateTime.ofInstant(
Instant.ofEpochMilli(myFile.lastModified()), ZoneId.systemDefault()
);
System.out.println(date);
}else{
System.out.println("File not exist!");
}
关于Java 文件最后一次修改是在默认时区吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50736168/