您的位置:首页 > 其它

时间间隔计算(分钟前,今天,昨天,过去的时间)

2017-07-05 11:16 281 查看
public static String getInterval(String createtime) throws ParseException { //传入的时间格式必须类似于2017-07-07 17:41:00这样的格式
String interval = null;

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date d = (Date) sd.parse(createtime, pos);

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createtime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar nowtime = Calendar.getInstance();
nowtime.setTime(new Date());
//用现在距离1970年的时间间隔new Date().getTime()减去以前的时间距离1970年的时间间隔d.getTime()得出的就是以前的时间与现在时间的时间间隔
long time = new Date().getTime() - d.getTime();// 得出的时间间隔是毫秒
if(time/60000 < 60 && time/60000 > 0) {
//如果时间间隔小于60分钟则显示多少分钟前
int m = (int) ((time%3600000)/60000);//得出的时间间隔的单位是分钟
interval = m + "分钟前";
}else if((nowtime.get(nowtime.DAY_OF_YEAR)-calendar.get(calendar.DAY_OF_YEAR))==0){
if(calendar.get(Calendar.HOUR_OF_DAY)<10){
if(calendar.get(Calendar.MINUTE)<10){
interval = "今天0"+calendar.get(Calendar.HOUR_OF_DAY)+":0"+calendar.get(Calendar.MINUTE);
}else{
interval = "今天0"+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE);
}
}else{
if(calendar.get(Calendar.MINUTE)<10) {
interval = "今天"+calendar.get(Calendar.HOUR_OF_DAY)+":0"+calendar.get(Calendar.MINUTE);
}else{
interval = "今天"+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE);
}

}
}else if((nowtime.get(nowtime.DAY_OF_YEAR)-calendar.get(calendar.DAY_OF_YEAR))==1){
if(calendar.get(Calendar.HOUR_OF_DAY)<10){
if(calendar.get(Calendar.MINUTE)<10) {
interval = "昨天0" + calendar.get(Calendar.HOUR_OF_DAY) + ":0" + calendar.get(Calendar.MINUTE);
}else{
interval = "昨天0" + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
}
}else {
if(calendar.get(Calendar.MINUTE)<10) {
interval = "昨天" + calendar.get(Calendar.HOUR_OF_DAY) + ":0" + calendar.get(Calendar.MINUTE);
}else{
interval = "昨天" + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
}
}
}else {
//超过24小时显示正常的时间,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
ParsePosition pos1 = new ParsePosition(0);
Date d1 = (Date) sdf.parse(createtime, pos1);
interval = sdf.format(d1);
}
return interval;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: