获取文件的最后修改日期/时间作为本地日期/时间字符串

Mus*_*ful 6 java file-attributes java-8

new File(url).lastModified()返回long等于自纪元以来的毫秒数(基于 GMT)。

将其转换为String代表系统本地日期/时间的简单方法是什么?

如果你真的需要看到我在这里的尝试,那就是,但这是一团糟,而且无论如何都是错误的:

LocalDateTime.ofEpochSecond(new File(url).lastModified()/1000,0,ZoneOffset.UTC).atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))
Run Code Online (Sandbox Code Playgroud)

除此之外,LocalDateTime我只是不知道时间 API 是如何工作的。

Tun*_*aki 6

要获取文件的最后修改时间,您应该使用Java NIO.2 API,它可以直接解决您的问题:

FileTime fileTime = Files.getLastModifiedTime(Paths.get(url));
System.out.println(fileTime); // will print date time in "YYYY-MM-DDThh:mm:ss[.s+]Z" format
Run Code Online (Sandbox Code Playgroud)

如果要访问其他属性(例如上次访问时间、创建时间),可以使用 读取路径的基本属性Files.readAttributes(path, BasicFileAttributes.class)

  • @tennenrishin是的,您可以使用 [`toInstant()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/attribute/FileTime.html#toInstant- -) 并使用 [`DateTimeFormatter`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) 对其进行格式化。 (2认同)