21.Android 时间工具DateUtil
String 转换 Date
/**
* String 转换 Date
*
* @param str
* @param format
* @return
*/
public static Date string2Date(String str, String format) {
try {
return new SimpleDateFormat(format).parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return new Date();
}
long 转换 String
/**
* Date(long) 转换 String
*
* @param time
* @param format
* @return
*/
public static String date2String(long time, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
String s = sdf.format(time);
return s;
}
long 去除 时分秒
/**
* long 去除 时分秒
* 时分秒全部为0
*
* @param date
* @return
*/
public static long getYearMonthDay(long date) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
计算时间差
/**
* 获取目标时间和当前时间之间的差距
*
* @param date
* @return
*/
public static String getTimestampString(Date date) {
Date curDate = new Date();
long splitTime = curDate.getTime() - date.getTime();
if (splitTime < (30 * ONE_DAY)) {
if (splitTime < ONE_MINUTE) {
return "刚刚";
}
if (splitTime < ONE_HOUR) {
return String.format("%d分钟前", splitTime / ONE_MINUTE);
}
if (splitTime < ONE_DAY) {
return String.format("%d小时前", splitTime / ONE_HOUR);
}
return String.format("%d天前", splitTime / ONE_DAY);
}
String result;
result = "M月d日 HH:mm";
return (new SimpleDateFormat(result, Locale.CHINA)).format(date);
}
24小时制转12小时制
/**
* 24小时制 转换 12小时制