首页 > 技术文章 > java 计算距离现在几分,几个小时,几天

xiaohaizhuimeng 2016-10-14 10:52 原文

 Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
   String stroldnow = dateFormat.format( now );
   Date newdate =TextUtil.stringToDateYYYYMM(stroldnow);
Date newdateTime=TextUtil.addDate(newdate,2);
   String newtime=dateFormat.format( newdateTime );
   Long returnstr=TextUtil.dateDiff(stroldnow, newtime, "yyyy/MM/dd HH:mm:ss");

 

共用方法:

/**
* 比较两个世间差
* @param startTime
* @param endTime
* @param format
* @return
*/
public static String dateDiff(String startTime, String endTime,
String format) {
// 按照传入的格式生成一个simpledateformate对象
SimpleDateFormat sd = new SimpleDateFormat(format);
long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
long nh = 1000 * 60 * 60;// 一小时的毫秒数
long nm = 1000 * 60;// 一分钟的毫秒数
long ns = 1000;// 一秒钟的毫秒数
long diff;
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
long time=0;
String strTime="";
// 获得两个时间的毫秒时间差异
try {
diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
day = diff / nd;// 计算差多少天
hour = diff % nd / nh + day * 24;// 计算差多少小时
min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
sec = diff % nd % nh % nm / ns;// 计算差多少秒
// 输出结果
//System.out.println("时间相差:" + day + "天" + (hour - day * 24) + "小时"
// + (min - day * 24 * 60) + "分钟" + sec + "秒。");
// System.out.println("hour=" + hour + ",min=" + min);
if(day>=1){
time=day;
strTime=time+"天前";
}
else if(hour>=1 && hour<24){
time=hour;
strTime=time+"小时前";
}
else{
if(min==0)
time=1;
time=min;
strTime=time+"分钟前";
}
// if (str.equalsIgnoreCase("h")) {
// return hour;
// } else {
// return min;
// }

} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// if (str.equalsIgnoreCase("h")) {
// return hour;
// } else {
// return min;
// }
return strTime;
}

推荐阅读