我们前端和后台打交道都是用到时间戳如:1509330651,但我显示给用户看的都是各种格式的时间字符串:yyyy年MM月dd日 ,HH:mm。
不多说直接上代码:
/**
* 时间相关工具类
*/
public class TimeUtil {
/**
* 以指定字符串形式返回当前系统时间
*/
public static String getSystem() {
SimpleDateFormat format = new SimpleDateFormat(Constant.cformatsecond,Locale.getDefault());
Date date = new Date(System.currentTimeMillis());
String s = format.format(date);
return s;
}
/**
* 时间戳转成指定字符串
*/
public static String long2time(long time, String formatStyle) {
SimpleDateFormat format = new SimpleDateFormat(formatStyle,Locale.getDefault());
Date date = new Date(time);
String s = format.format(date);
return s;
}
/**
* 指定字符串转为时间戳
*
* @param time
* 指定字符串
* @param formatStyle
* 字符串格式
*/
public static long time2long(String time, String formatStyle) {
SimpleDateFormat format = new SimpleDateFormat(formatStyle,Locale.getDefault());
Date date;
try {
date = format.parse(time);
} catch (ParseException e) {
date = new Date();//如果格式错误就返回当前时间搓
e.printStackTrace();
Logs.d(e.getMessage());
}
return date.getTime();
}
/**
* 根据一段时间戳返回耗时时间字符
*/
public static String long2time(long time) {
String str = "";
long h = 60 * 60 * 1000;
long m = 60 * 1000;
long s = 1000;
if (time > h) {
long hh = time / h;
long mm = time / m;
long ss = time / s;
str = hh + "小时" + mm + "分钟" + ss + "秒";
} else if (time > m) {
long mm = time / m;
long ss = time / s;
str = mm + "分钟" + ss + "秒";
} else {
long ss = time / s;
str = ss + "秒";
}
return str;
}
}
long time:就是时间搓
String formatString:自定义的时间字符串格式 如:
/* 时间格式 */
public final static String cformatDay = "yyyy年MM月dd日";
public final static String cformatD = "M月d日";
public final static String cformatsecond = "yyyy年MM月dd日HH时mm分ss秒";
public final static String formatminute = "HH:mm";
public final static String formatsecond = "yyyy-MM-dd HH:mm:ss";
* HH:mm 15:44 * h:mm a 3:44 下午 * HH:mm z 15:44 CST * HH:mm Z 15:44 +0800 * HH:mm zzzz 15:44 中国标准时间 * HH:mm:ss 15:44:40 * yyyy-MM-dd 2016-08-12 * yyyy-MM-dd HH:mm 2016-08-12 15:44 * yyyy-MM-dd HH:mm:ss 2016-08-12 15:44:40 * yyyy-MM-dd HH:mm:ss zzzz 2016-08-12 15:44:40 中国标准时间 * EEEE yyyy-MM-dd HH:mm:ss zzzz 星期五 2016-08-12 15:44:40 中国标准时间 * yyyy-MM-dd HH:mm:ss.SSSZ 2016-08-12 15:44:40.461+0800 * yyyy-MM-dd'T'HH:mm:ss.SSSZ 2016-08-12T15:44:40.461+0800 * yyyy.MM.dd G 'at' HH:mm:ss z 2016.08.12 公元 at 15:44:40 CST * K:mm a 3:44 下午 * EEE, MMM d, ''yy 星期五, 八月 12, '16 * hh 'o''clock' a, zzzz 03 o'clock 下午, 中国标准时间 * yyyyy.MMMMM.dd GGG hh:mm aaa 02016.八月.12 公元 03:44 下午 * EEE, d MMM yyyy HH:mm:ss Z 星期五, 12 八月 2016 15:44:40 +0800 * yyMMddHHmmssZ 160812154440+0800 * yyyy-MM-dd'T'HH:mm:ss.SSSZ 2016-08-12T15:44:40.461+0800 * EEEE 'DATE('yyyy-MM-dd')' 'TIME('HH:mm:ss')' zzzz 星期五 DATE(2016-08-12) TIME(15:44:40) 中国标准时间