簡體   English   中英

如何將文件上次修改的時間戳轉換為日期?

[英]How to convert the file last modified timestamp to a date?

如何將File#lastModified()轉換為真實日期? 格式並不重要。

Date d = new Date(file.lastModified());

lastModified()返回自 1970-01-01 以來的毫秒數, Date類也以相同的方式存儲其時間。 Date(long)構造函數需要這些毫秒,並用它初始化Date

只需使用SimpleDateFormat類將 long 轉換為 date。 只有你執行代碼:

new SimpleDateFormat("dd-MM-yyyy HH-mm-ss").format(
    new Date(new File(filename).lastModified()) 
);

你得到的是一個很長的數字,表示從 1970 年 1 月 1 日起經過的毫秒數。這是表示日期的標准方式。

嘗試這個:

java.util.Date myDate = new java.util.Date(theFile.lastModified());

現在您手頭有一個 Date 對象。

您可以使用SimpleDateFormat以更可愛的方式打印該日期。

  1. 獲取上次修改的時間戳,如您問題的副本所述

  2. 創建一個新的Date對象或Calendar對象。 new Date(timestamp) 或者Calendar.getInstance()然后調用setTimeInMillis(timestamp) 顧名思義,時間戳實際上是一個毫秒數(自 1970 年 1 月 1 日以來)

  3. 然后您可以通過java.text.SimpleDateFormat格式化日期

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM