user2576816
user2576816

Reputation: 11

How to round time to nearest 15 minute in java

My program needs to calculate the overtime periods of workers for salary calculation purposes. To this end, what I am doing now is getting the worker's clock-in time and out time, then I calculate with the company's time scales and get how many hours overtime each worker has done. I need to round these times to the nearest 15 minutes, so I need a class to pass in the hours and return the rounded hours.

For example:

Upvotes: 1

Views: 9369

Answers (3)

Ankush G
Ankush G

Reputation: 1081

If you just can get minutes extracted from the time and pass it to this function:

public static int getNear15Minute(int minutes){
        int mod = minutes%15; 
        int res = 0 ;
        if((mod) >=8){
            res = minutes+(15 - mod);
        }else{
            res = minutes-mod;
        }
        return res; //return rounded minutes
    }

here I assumed number greater than or equal to 8 is near to 15.

Upvotes: 4

AxelH
AxelH

Reputation: 14572

Well, rounding is easy to do with a modulo operation.

Here you want to round to a 15minutes.

Using the epoch time in milliseconds, you just need to remove the remainder of the modulo operation like this :

long l = System.currentTimeMillis();
l -= l % (15*60*1000);


System.out.println(new Date(System.currentTimeMillis()));
System.out.println(new Date(l));

Tue Jan 03 09:35:56 CET 2017

Tue Jan 03 09:30:00 CET 2017

15*60*1000 is simply the number of milliseconds in 15minutes

You just need to check the value of the remainder to add 15minute if need. So just store the remainder :

long r = l % (15*60*1000);

Then substract it to the current time

l -= r;

And check the number of minute (depends on the precision you really wants.

if( r / 60_000 >= 8)
     l += 15*60*1000;

This will round up if the quarter is past from 8minutes (if this really means anything in english ;) )

Full code :

long l = System.currentTimeMillis();
long r = l % (15*60*1000);
l -= r;
if( r / 60_000 >= 8)
     l += 15*60*1000;

Upvotes: 1

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26647

Example that uses current Date

import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int round = calendar.get(Calendar.MINUTE) % 15;
        calendar.add(Calendar.MINUTE, round < 8 ? -round : (15-round));
        calendar.set( Calendar.SECOND, 0 );
        System.out.println(calendar.getTime());
    }
}

Test

Tue Jan 03 09:15:00 CET 2017

Online demo

Upvotes: 0

Related Questions