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秒