类似新浪微博发布时间显示方式 比如 **分钟前 ** 小时前 昨天12:30 前天13:30等

来源:互联网 发布:catia软件培训 编辑:程序博客网 时间:2024/05/01 15:06
public static String getDayTime(String daytime){ //daytime 格式为yyyy-MM-dd HH:mm:ss
int mimutes = 0; 
int days = 0;
int hours = 0;
String timeStr = "";
Date nowdate = new Date();
Date createdate = null;
if (daytime != null && !"".equals(daytime) && daytime.length()==19) {
try {
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat format = new SimpleDateFormat(pattern);
createdate = format.parse(daytime);
} catch (ParseException e) {
e.printStackTrace();
}

if (nowdate.getDate()==createdate.getDate() && nowdate.getMonth() == createdate.getMonth() && nowdate.getYear() == createdate.getYear()) {
mimutes = TimeUtility.getMinutesDiff(nowdate,createdate);
if (mimutes == 0) {
timeStr = "刚刚";
}else if (mimutes > 0) {
if (mimutes > 0 && mimutes < 60) {
timeStr = String.valueOf(mimutes) + "分钟前";
}else{
hours = mimutes/24;
if (hours > 0 && hours <= 24) {
timeStr = String.valueOf(hours) + "小时前";
}
}
}
}else{
//int daysDiff = getDaysDiff(nowdate,createdate);
if (nowdate.getMonth() == createdate.getMonth()) {
days = nowdate.getDate() - createdate.getDate();
}else{
days = nowdate.getDate()+getDaysOfMonth(createdate) - createdate.getDate();
}

if (days == 1  ) {
timeStr = "昨天" + daytime.substring(10,16);
}else if (days == 2 ) {
timeStr = "前天" + daytime.substring(10,16);
}else{
timeStr = daytime.substring(0,16);
}
}
}

return timeStr;

}

/**
* 获取指定日期的月份总共有多少天
* @param date
* @return
*/
public static int getDaysOfMonth(Date date){
Calendar aCalendar = Calendar.getInstance(); 
aCalendar.setTime(date); 
aCalendar.add(Calendar.MONTH, 1);
aCalendar.add(Calendar.DAY_OF_MONTH, -1); 
date = aCalendar.getTime();
return date.getDate();
}