您的位置:首页 > 编程语言 > Java开发

java数字格式化, 时间换算工具方法

2015-07-30 11:28 567 查看

java数字格式化, 时间换算工具方法

Java格式化数字——右对齐,左补0

方法一

DecimialFormat format = new DecimialFormat("00");
int number = 9;
System.out.println(format.format(number));

// 应该输出 09


方法二

String str2 = String.format("%04d", number2);


时间差换算成字符串方法

最开始没有考虑到integer的大小范围,出现了没法判断到周的情况,这个方法解决了这个问题

/**
* 计算两个日期型的时间相差多少时间
*
* @return
*/
public static String getTimeDiff(Date postDate) {
Date currentDate = new Date();

if (postDate == null || currentDate == null) {
return null;
}
long timeLong = currentDate.getTime() - postDate.getTime();

long secondScope = 60*1000;
long minuteScope = secondScope*60;
long hourScope = minuteScope*24;
long dayScope = hourScope*7;
long weekScope = dayScope*4;
long monthScope = weekScope*12;

if (timeLong < secondScope)  // 小于60秒
return timeLong / 1000 + "秒前";
else if (timeLong < minuteScope) {  // 小于60分钟
timeLong = timeLong / secondScope;
return timeLong + "分钟前";
} else if (timeLong < hourScope) {      // 小于24小时
timeLong = timeLong / minuteScope;
return timeLong + "小时前";
} else if (timeLong < dayScope) {       // 小于7天
timeLong = timeLong / hourScope;
return timeLong + "天前";
} else if (timeLong < weekScope) {      // 小于4周
timeLong = timeLong / dayScope;
return timeLong + "周前";
} else if(timeLong < monthScope){
timeLong = timeLong / weekScope;
return timeLong + "月前";
} else {
SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATE_PATTERN2);
return sdf.format(postDate);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: