Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date rounding

Tags:

java

I would like an elegant way to round a java Date up or down to the nearest minute (or second, hour, day).

For example a date of "Wed Jan 25 10:36:34 GMT 2012" rounded up to the nearest minute would be "Wed Jan 25 10:37:00 GMT 2012"

like image 258
darrenmc Avatar asked Jan 25 '12 10:01

darrenmc


People also ask

How to round off minutes in Java?

You can do this logic raw using the primative long . For example: long now = System. currentTimeMillis(); long rounded = now - now % 60000; Once you have a long you can do whatever you want.

Is there a datatype for date in Java?

The Date in Java is not only a data type, like int or float, but a class. This means it has its own methods available for use. A Date in Java also includes the time, the year, the name of the day of the week, and the time zone.

How do you add and subtract dates in Java?

DATE field can be used to add or subtract dates in Java. Positive value passed into add() method will add days into date while negative values will subtract days from date in Java. Similarly Calendar. MONTH can be used to add and subtract months from date in Java.


1 Answers

If you use Apache commons-lang, you can use DateUtils to round your dates:

Date now = new Date(); Date nearestMinute = DateUtils.round(now, Calendar.MINUTE); 
like image 195
Guido Avatar answered Sep 19 '22 19:09

Guido