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;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值