2011-08-12 77 views
0
roundMinutes

我試圖讓小時和分鐘,然後一輪分鐘到最近的5,我發現與roundMinutes功能這裏的Java日曆類:enter link description here在Java中使用

我怎麼會在代碼中使用此?我已經嘗試創建一個日曆對象,一個日期對象,但沒有任何顯示我使用此方法。提供一個例子會很棒!

+0

林不知道的API,是的,但它不是爲標準的Java Calendar類。以下是日曆的Java 7文檔。 http://download.oracle.com/javase/7/docs/api/java/util/Calendar.html –

+0

雖然它並不直接回答你的問題,你可能需要使用約達時間,只要你做的有日期的東西,而不是內置的類。 http://joda-time.sourceforge.net/ –

+0

我以前回答過類似的問題,其中OP要四捨五入到最接近的季度。看看這裏:http://stackoverflow.com/questions/3553964/how-to-round-time-to-the-nearest-quarter-in-java/3553994#3553994 –

回答

2

確保您使用的thisCalendar。有在java中的默認日曆沒有roundMinutes

calendar.roundMinutes(5, Calendar.ROUND_UP) if you want 5:41 to become 5:45 
calendar.roundMinutes(5, Calendar.ROUND_DOWN) if you want 5:41 to become 5:40 

calendar.roundMinutes(5, Calendar.ROUND_AUTO) if you want 5:41 to become whatever the library thinks is normal. 

ROUND_DOWN

1

我不知道最近的5分鐘,但下面的代碼將四捨五入到下一分鐘:

Date now = new Date(); 
Date nearestMinute = DateUtils.round(now, Calendar.MINUTE); 

也許你可以繼續形式有:d

2

以下代碼將給定的約達日期時間舍入爲5分鐘以上

DateTime dt = timeEnded.minuteOfDay().roundCeilingCopy(); 

int minutes = dt.getMinuteOfHour(); 
int mod = minutes % 5; 
int add = 5 - mod; //add this to our datetime 

DateTime roundedTo5 = dt.plusMinutes(add);