2013-04-08 63 views
-1

Java代碼的如何在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(); 
    } 
} 

目前,我正在使用此代碼一輪毫秒值。在這種方法中,代碼冗餘是一個大問題。

有沒有更好的解決方案或數學公式來計算?

回答

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

注缺少的switchbreakreturn語句。這導致switch塊中的語句到經過到下一個case標籤。

這涵蓋在tutorial

0

是不是隻有calender.set(Calendar.MILLISECOND, 0)足夠?

另一種方式來做到這一點是:

return date.getTime()/1000 * 1000; 
0

您可以在switch語句採取 '下通' 的優勢:

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

}