Obtain last modification date/time of file as local date/time string

落爺英雄遲暮 提交于 2020-01-01 12:26:08

问题


new File(url).lastModified() returns a long equal to the number of milliseconds since the epoch, which is GMT-based.

What is a simple way to convert this to a String representing system-local date/time?

If you really need to see an attempt from me here it is but it's a terrible mess and it's wrong anyway:

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

Beyond LocalDateTime I just have no idea how the time API works.


回答1:


To get the last modified time of a file, you should use Java NIO.2 API, which directly resolves your problem:

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

If you want to access other properties (like last access time, creation time), you can read the basic attributes of a path with Files.readAttributes(path, BasicFileAttributes.class).



来源:https://stackoverflow.com/questions/33366031/obtain-last-modification-date-time-of-file-as-local-date-time-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!