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