常用時間處理方法:時間戳和格式化時間之間轉換;時間比大小
阿新 • • 發佈:2019-02-18
1、獲取當前格式化時間:
// 獲取當前時間的時間戳,並轉換成格式化時間
long getNowTimeLong = System.currentTimeMillis();
//轉換成12小時進位制
SimpleDateFormat fromatTime_12 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time_12 = fromatTime_12.format(getNowTimeLong);
System.out.println("time_12---"+time_12);
//轉換成24小時進位制
SimpleDateFormat fromatTime_24 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time_24 = fromatTime_24.format(getNowTimeLong);
System.out.println("time_24---"+time_24);
2、兩個時間比大小(工具類形式給出)
public static int compare_date(String DATE1, String DATE2) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return -2;
}
注:注意引數格式,要和方法裡的SimpleDateFormat指定的格式一致
3、格式化時間轉成時間戳
// 格式化時間,轉換成long型別
Date date = null;
String dateString = "2016-04-08 16:30:50";
SimpleDateFormat formatTiem2long = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = formatTiem2long.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
long longFormatTime = date.getTime();
// 有時候,自己電腦或者手機上的時間,會和伺服器差8個小時,這個時候,就用下面註釋的這句。看情況而定
// long longFormatTime = date.getTime() - 28800000;
System.out.println("longFormatTime--" + longFormatTime);
4、時間戳轉成格式化時間
// long型別的時間戳,轉換成格式化時間
SimpleDateFormat long2FormatTime = new SimpleDateFormat("yyyy年MM月dd日HH時mm分ss秒");
String re_StrTime = long2FormatTime.format(new Date(longFormatTime));
System.out.println("re_StrTime--" + re_StrTime);
驗證3、4方法時,將3的格式化時間變成時間戳,然後把得到的時間戳用4變成格式化時間,對比可知
方法3、4的結果
longFormatTime--1460104250000
re_StrTime--2016年04月08日16時30分50秒