日期取整(日期精度调节,如调节至秒/分等)
问题提出:日期取整
解决方法:使用DateUtils。DateUtils.round()
can round to almost every Calender field, 包括Calender.YEAR,Calendar.SECOND,Calendar.MINUTE,Calendar.HOUR,Calendar.DAY_OF_MONTH,Calendar.MONTH.
使用举例:
 
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;

FastDateFormat dtFormat 
= DateFormatUtils.ISO_DATETIME_FORMAT;

Date now 
= new Date( );

Date nearestHour 
= DateUtils.round( now, Calendar.HOUR );
Date nearestDay 
= DateUtils.round( now, Calendar.DAY_OF_MONTH );
Date nearestYear 
= DateUtils.round( now, Calendar.YEAR );

System.out.println( 
"Now: " + dtFormat.format( now ) );
System.out.println( 
"Nearest Hour: " + dtFormat.format( nearestHour ) );
System.out.println( 
"Nearest Day: " + dtFormat.format( nearestDay ) );
System.out.println( 
"Nearest Year: " + dtFormat.format( nearestYear ) );

DateUtils.round()相当于数学中的四舍五入法取整,而DateUtils.truncate()相当与去余法取整。
评论
发表评论

您还没有登录,请登录后发表评论