java System.currentTimeMillis()毫秒值和具體日期值互相轉換


System.currentTimeMillis()與日期 間是可以相互轉換的,通過

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dateStr = dateformat.format(System.currentTimeMillis());

可以獲取如“ 2016-09-02 23:02:17 ”這樣的一個字符串,但是反過來呢?如果給我們一個“ 2016-09-02 23:02:17 ”字符串,我們能否得到當前日期對應的毫秒值呢? 答案是肯定的。

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try {

       long time = dateformat.parse("2016-09-02 23:02:17").getTime();

       System.out.println(time);

}

catch (ParseException e) {

                     e.printStackTrace();

}

輸出:1472828537000; 
由此可見,毫秒值與日期之間是可以互轉的。

總結:測試時候可能會出現當前獲取的毫秒值轉換為日期后,再轉為毫秒值時候 與前者不一致,這個是因為獲取的是毫秒值,而轉換為日期后是以秒為單位了,所以轉換后才會出現這種情況。 解決方法:在時間格式化的時候寫成

SimpleDateFormat dateformat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM