Java 代码
public static long round(long millis , TimeUnit unit){
Calendar calendar = Calendar.getInstance();
switch(unit){
case DAYS:
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTimeInMillis();
case HOURS:
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
return calendar.getTimeInMillis();
case MINUTES:
calendar.set(Calendar.MILLISECOND , 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTimeInMillis();
case SECONDS:
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
case MILLISECONDS:
default:
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
}
目前,我正在使用此代码对毫秒值进行舍入。在这种方法中,代码的冗余是一个大问题。
有没有更好的解决方案或数学方程来计算这个?