System.currentTimeMillis()產生一個當前的毫秒,這個毫秒其實就是自1970年1月1日0時起的毫秒數,Date()其實就是相當於Date(System.currentTimeMillis()); 因為Date類還有構造Date(long date),用來計算long秒與1970年1月1日之間的毫秒差。得到了這個毫秒數,我們自己也可以算起現在的年月日周時。
當時近期在使用new Date()方法獲取系統當前時間,有時會發現得到的時間和系統時間不一致,慢了8小時,如:2020-01-08 20:24 使用此方法獲取當前時間,得到的結果卻是2020-01-08 12:24 為了解決這個問題,可以參考以下這串代碼:
Date date = new Date();//加8個時區
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
date = calendar.getTime();