-1

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();
    }
}

目前,我正在使用此代码对毫秒值进行舍入。在这种方法中,代码的冗余是一个大问题。

有没有更好的解决方案或数学方程来计算这个?

4

4 回答 4

3

您可以通过像这样利用下降来消除所有重复的行:

public static long round(long millis , TimeUnit unit){
    Calendar calendar = Calendar.getInstance();
    switch(unit){
        case DAYS:
            calendar.set(Calendar.HOUR, 0);
        case HOURS:
            calendar.set(Calendar.MINUTE, 0);
        case MINUTES:
            calendar.set(Calendar.SECOND, 0);
        case SECONDS:
        case MILLISECONDS:
        default:
            calendar.set(Calendar.MILLISECOND, 0);
    }
    return calendar.getTimeInMillis();
}
于 2013-04-08T14:02:06.493 回答
1
public static long round(long millis , TimeUnit unit){
    Calendar calendar = Calendar.getInstance();
    switch(unit){
        case DAYS:
            calendar.set(Calendar.HOUR, 0);
        case HOURS:
            calendar.set(Calendar.MINUTE, 0);
        case MINUTES:
            calendar.set(Calendar.SECOND, 0);
        default:
            calendar.set(Calendar.MILLISECOND, 0);
    }
    return calendar.getTimeInMillis();
}

注意里面没有breakorreturn语句switch。这会导致switch块中的语句落入下一个case标签。

教程中对此进行了介绍。

于 2013-04-08T14:02:40.453 回答
0

calender.set(Calendar.MILLISECOND, 0)不够吗?

另一种方法是:

return date.getTime() / 1000 * 1000;
于 2013-04-08T14:02:43.540 回答
0

您可以在 switch 语句中利用“fallthrough”:

public static long round(long millis , TimeUnit unit){
    Calendar calendar = Calendar.getInstance();
    switch(unit){
        case DAYS:
            calendar.set(Calendar.HOUR, 0);
        case HOURS:
            calendar.set(Calendar.MINUTE, 0);
        case MINUTES:
            calendar.set(Calendar.SECOND, 0);
        case SECONDS:
            calendar.set(Calendar.MILLISECOND, 0);
    }
    return  calendar.getTimeInMillis();

}
于 2013-04-08T14:04:34.193 回答