安卓开发:DateUtils

时间:2022-08-31 17:42:46
public class DateUtils{
/**
* 显示友好时间
*
* @param ms
* @return
*/
public static String getTimeDes(long ms) {
int ss = 1000;
int mi = ss * 60;
int hh = mi * 60;
int dd = hh * 24;
long day = ms / dd;
long hour = (ms - day * dd) / hh;
long minute = (ms - day * dd - hour * hh) / mi;
long second = (ms - day * dd - hour * hh - minute * mi) / ss;
long milliSecond = ms - day * dd - hour * hh - minute * mi - second
* ss;
String str = "";
if (day > 0) {
str += day + "天";
}
if (hour > 0) {
str += hour + "小时";
}
if (minute > 0) {
str += minute + "分";
}
if (second > 0) {
str += second + "秒";
}
return str;
} /**
*
* @param beginTime
* @param _endTime
* @return 计算两个日期之间相差的天数
*/
public static double getDecreaseDays(String beginTime, String _endTime) {
String str1 = beginTime; //"yyyyMMdd"格式 如 20131022
String str2 = _endTime; //"yyyyMMdd"格式 如 20131022
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");//输入日期的格式
Date date1 = null;
try {
date1 = simpleDateFormat.parse(str1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = simpleDateFormat.parse(str2);
} catch (ParseException e) {
e.printStackTrace();
}
GregorianCalendar cal1 = new GregorianCalendar();
GregorianCalendar cal2 = new GregorianCalendar();
cal1.setTime(date1);
cal2.setTime(date2);
double dayCount = (cal2.getTimeInMillis() - cal1.getTimeInMillis()) / (1000 * 3600 * 24);//从间隔毫秒变成间隔天数
return dayCount;
} /**
* 计算出endDate之前days天的日期
*
* @param endDate
* @param days
* @return
*/
public static String getDate(String endDate, int days) {
String str1 = endDate; //"yyyyMMdd"格式 如 20131022
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");//输入日期的格式
Date date1 = null;
try {
date1 = simpleDateFormat.parse(str1);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
now.setTime(date1);
now.set(Calendar.DATE, now.get(Calendar.DATE) - days);
Date date = now.getTime();
return simpleDateFormat.format(date);
} }