Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java how do we round off time to nearest hour and minute?

Tags:

java

time

I have a String which has the time. I need to round it off to the nearest hour and also the nearest minute. How do I do it in java? Ex: String time="12:58:15"; I need to round it off to 1:00:00 and also 12:58:00

like image 810
Srinivas Avatar asked Nov 22 '11 20:11

Srinivas


1 Answers

For calendar operations you have to use Calendar class. In your case you would do something like this:

package test;

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

public class TestDate {

    public static void main(String[] args) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.HOUR_OF_DAY, 12);
        c.set(Calendar.MINUTE, 58);
        c.set(Calendar.SECOND, 15);
        Date d = c.getTime();

        System.out.println("Start point: " + d.toString());
        System.out.println("Nearest whole minute: " + toNearestWholeMinute(d));
        System.out.println("Nearest whole hour: " + toNearestWholeHour(d));
    }

    static Date toNearestWholeMinute(Date d) {
        Calendar c = new GregorianCalendar();
        c.setTime(d);

        if (c.get(Calendar.SECOND) >= 30)
            c.add(Calendar.MINUTE, 1);

        c.set(Calendar.SECOND, 0);

        return c.getTime();
    }

    static Date toNearestWholeHour(Date d) {
        Calendar c = new GregorianCalendar();
        c.setTime(d);

        if (c.get(Calendar.MINUTE) >= 30)
            c.add(Calendar.HOUR, 1);

        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);

        return c.getTime();
    }

}

And the result:

Start point: Tue Nov 22 12:58:15 CET 2011
Nearest whole minute: Tue Nov 22 12:58:00 CET 2011
Nearest whole hour: Tue Nov 22 13:00:00 CET 2011
like image 135
Fernando Miguélez Avatar answered Sep 20 '22 06:09

Fernando Miguélez