Link to home
Create AccountLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

Rounding a time in milliseconds to nearest minute?

Hi,

I am getting the current time like:

    now = System.currentTimeMillis();

I want to find the closest minute, 5 minutes from now, with ceil():

    now = 10:45:12
    +5min = 10:50:12
    +5minAndCeil = 10:51:00

So getting the +5min time is simple:

    now = System.currentTimeMillis();
    +5min = now + (60 * 1000 * 5);

But are there any good methods of rounding that number up to the closest minute?

Thanks
Avatar of Mick Barry
Mick Barry
Flag of Australia image

How is ceil() not working for you?

you can also use BigDecimal to control how the rounding is done
http://helpdesk.objects.com.au/java/how-to-round-decimal-value-using-bigdecimal

alternatively you could use the calendar class to clear seconds and add one minute
http://helpdesk.objects.com.au/java/how-do-i-add-a-specified-number-of-minutes-to-a-java-date
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
try this :
static final long MILLISECONDS_PER_MINUTE = 60 * 1000L;
long msRem = now % MILLISECONDS_PER_MINUTE;
If (msRem < 1000) now = now - msRem; else now = now - msRem + MILLISECONDS_PER_MINUTE;
Try the following (where 'nowPlusFive'  is type Date and 'ONE_MIN' is defined as 1 * 60 * 1000)
Date newD = new Date((nowPlusFive.getTime() + ONE_MIN) / ONE_MIN * ONE_MIN);

Open in new window