Date類的很多獲取時間的方法都被棄用了,現有的比較常用的方法是Date.getTime(),這個方法可以獲取Date類型時間的時間戳。
時間戳:用當前時間的時間毫秒數減去1970/1/1 08:00:00的毫秒數,就是當前時間的時間戳。所以時間戳的默認時間單位是毫秒,轉換的時候需要注意。
字符串轉時間戳
/**
* @desc 字符串轉時間戳
* @param String time
* @example time="2019-04-19 00:00:00"
**/
public Long getTimestamp(String time) {
Long timestamp = null;
try {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
時間戳轉字符串
/**
* @desc 時間戳轉字符串
* @param Long timestamp
* @example timestamp=1558322327000
**/
public String getStringTime(Long timestamp) {
String date = new SimpleDateFormat("yyyy-MM-dd").format(timestamp.getTime())); // 獲取只有年月日的時間
String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp.getTime())); // 獲取年月日時分秒
return datetime;
}
