0

I am trying to get the hour and minute and then round the minutes to the nearest 5. I found the java Calendar class with the roundMinutes function here: enter link description here

How would I use this in code? I have tried creating a Calendar object, a Date object, but nothing shows me this method to use. Providing an example would be great!

taraloca
  • 9,077
  • 9
  • 44
  • 77
  • Im not sure what API that is, but it isnt for the Standard Java Calendar class. Here is the Java 7 Documentation for Calendar. http://download.oracle.com/javase/7/docs/api/java/util/Calendar.html – Hunter McMillen Aug 12 '11 at 13:01
  • While it doesn't directly answer your question, you'll probably want to use Joda Time whenever you're doing something with dates, not the built-in classes. http://joda-time.sourceforge.net/ – Bart van Heukelom Aug 12 '11 at 13:03
  • I have previously answered a similar question where the OP wanted to round to the nearest quarter. Check it out here: http://stackoverflow.com/questions/3553964/how-to-round-time-to-the-nearest-quarter-in-java/3553994#3553994 – Sean Patrick Floyd Aug 12 '11 at 13:10
  • @BartvanHeukelom FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [*java.time*](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 18 '18 at 20:57

4 Answers4

2

The following code rounds a given joda DateTime to 5 minutes and up

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);
MLS
  • 237
  • 1
  • 5
2

Make sure you are using this Calendar. There is no roundMinutes in java's default calendar.

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. 

See ROUND_DOWN

Nivas
  • 18,126
  • 4
  • 62
  • 76
1

Be sure you are using the right Calendar class: org.rakeshv.utils.Calendar, assuming you are using the custom Util jar that Rakesh created.

Atreys
  • 3,741
  • 1
  • 17
  • 27
1

I'm not sure about the nearest 5 minutes but the following code will round to the next minute:

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

Perhaps you can proceed form there :D

gotomanners
  • 7,808
  • 1
  • 24
  • 39