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"
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With