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;
}
}
}
java取得格式化时间的最小刻度的整点时间
最新推荐文章于 2021-02-17 01:14:58 发布