2015-10-27 61 views
3

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)) 

超越LocalDateTime我只是不知道如何時API作品。

回答

3

獲取文件的最後修改時間,你應該使用Java API NIO.2,這直接解決您的問題:

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

如果要訪問其他屬性(如上次訪問時間,創建時間),您可以使用Files.readAttributes(path, BasicFileAttributes.class)來讀取路徑的基本屬性。

+0

是否可以格式化FileTime到不同的默認值,而不必先用'FileTime :: toMillis'回到原來的方式? – Museful

+1

@tennenrishin是的,你可以通過['toInstant()']獲得一個Instant(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)。 – Tunaki

+0

'DateTimeFormatter.ofPattern(「uuuu-MMM-dd HH:mm:ss」)。format(fileTime.toInstant())'throws' java.time.temporal.UnsupportedTemporalTypeException:Unsupported field:Year' for me。我究竟做錯了什麼? – Museful

相關問題