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

来源:互联网 发布:淘宝星期一 编辑:程序博客网 时间:2024/06/05 18:28

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);        }    }
0 0