`
lohasle
  • 浏览: 253837 次
社区版块
存档分类
最新评论

java取得格式化时间的最小刻度的整点时间

阅读更多
public class Test{  
 /**
     * 取得符合规范的data
     *
     * @param sourDate
     * @param pattern
     * @return
     */
    public static Date praseDateToDataByPattern(Date sourDate, String pattern) throws ParseException {
        if (sourDate == null || pattern == null) {
            throw new ParseException("错误的日期和格式化字符", 0);
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String result_date = sdf.format(sourDate);
        return sdf.parse(result_date);
    }

    /**
     * 取得格式化字符串的整点数据
     * 根据格式化的字符串的最小单位四舍五入的对时间进行操作
     * 如  2013-05-01 02:12:34  -->2013-05-01 02:13:00
     * 2013-05-01 02:12:12  -->2013-05-01 02:12:00
     *
     * @param date   日期
     * @param format 格式化的字符串
     * @return
     */
    public static String getCorrectDateOnEntire(Date date, String format) throws ParseException {
        if (date == null || format == null) {
            throw new ParseException("错误的日期和格式化字符", 0);
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        char[] ch = format.toCharArray();
        StringBuffer least_precision = new StringBuffer();
        for (int i = ch.length; i > 0; i--) {
            if (ch[ch.length - 1] == ch[i - 1]) {
                least_precision.append(ch[i - 1]);
            } else {
                break;
            }
        }
        Date run_date = praseDateToDataByPattern(date, format);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(run_date);
        int field = TimeAccuracy.valueOf(least_precision.toString()).textVal;
        int real_time = calendar.get(field);
        int possible_max_time = calendar.getMaximum(field);// 12小时制
        if (real_time > possible_max_time) {
            calendar.roll(field, true);
        } else {
            calendar.roll(field, calendar.getMinimum(field));
        }
        return sdf.format(calendar.getTime());
    }


    public static enum TimeAccuracy {
        yyyy(Calendar.YEAR),
        MM(Calendar.MONTH),
        dd(Calendar.DATE),
        HH(Calendar.HOUR),
        mm(Calendar.MINUTE),
        ss(Calendar.MILLISECOND);

        private int textVal;

        private TimeAccuracy(int textVal) {
            this.textVal = textVal;
        }

        private int getIntValue() {
            return textVal;
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics