Srinivas
Srinivas

Reputation: 565

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

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

Upvotes: 11

Views: 45033

Answers (6)

FrancescoM
FrancescoM

Reputation: 1400

Well, the best answer is the simplest one

  /**
   * 2020-01-01 10:00:55 is transformed into 2020-01-01 10:00:00
   * 2020-01-01 10:20:55 is transformed into 2020-01-01 10:00:00
   * 2020-01-01 10:30:01 is transformed into 2020-01-01 11:00:00
   * @return the Timestamp rounded to the nearest hour
   */
  public static Timestamp roundTimestampToNearestHour(Timestamp input){
    return Timestamp.from(Instant.ofEpochMilli(((input.getTime()+1800000)/(60000*60))*(60000*60)));
}

Upvotes: 0

Baked Inhalf
Baked Inhalf

Reputation: 3735

With Java 8 you can use a java.time.LocalDateTime or ZonedDateTime (timezone). This would get you started by rounding to the nearest hour:

String mytime = "2019-05-21 13:41:50";

// Convert String to LocalDateTime
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(mytime, dtf);

// If minutes equals 30 or more, add 1 hour
int minutes = localDateTime.getMinute();
if (minutes >= 30)
{
    localDateTime = localDateTime.plusHours(1);
}

// Round down
localDateTime = localDateTime.truncatedTo(ChronoUnit.HOURS)

// Back to String (OP wants the end result to be of type String)    
String roundedTime = dtf.format(localDateTime);
System.out.println(roundedTime);

For example: "2019-05-21 13:41:50" would be printed as 2019-05-21 14:00:00

Upvotes: 9

Fernando Miguélez
Fernando Miguélez

Reputation: 11316

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

Upvotes: 24

kazzaki
kazzaki

Reputation: 72

package com.xyz.util;

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

public class DateTimeUtils {

    public static void main(String[] args) {
        Date date = new Date();
        date.setHours(23);
        System.out.println("prev whole hour, millies: "+toWholeHour(date,-1)+", "+toWholeHour(date,-1).getTime());
        System.out.println("curr whole hour, millies: "+toWholeHour(date,0)+", "+toWholeHour(date,0).getTime());
        System.out.println("next whole hour, millies: "+toWholeHour(date,1)+", "+toWholeHour(date,1).getTime());

        System.out.println("prev whole minute, millies: "+toWholeMinute(date,-1)+", "+toWholeMinute(date,-1).getTime());
        System.out.println("curr whole minute, millies: "+toWholeMinute(date,0)+", "+toWholeMinute(date,0).getTime());
        System.out.println("next whole minute, millies: "+toWholeMinute(date,1)+", "+toWholeMinute(date,1).getTime());
    }

    public static Date toWholeHour(Date d, int beforeOrAfter) {
        Calendar c = new GregorianCalendar();
        c.setTime(d);
        c.add(Calendar.HOUR, beforeOrAfter);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    public static Date toWholeMinute(Date d, int beforeOrAfter) {
        Calendar c = new GregorianCalendar();
        c.setTime(d);
        c.add(Calendar.MINUTE, beforeOrAfter);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

}

Upvotes: 0

James A. N. Stauffer
James A. N. Stauffer

Reputation: 2659

Create a Date using SimpleDateFormat. Create GregorianCalendar from the Date. Roll the minutes or seconds by 30. Then set minutes or seconds to 0.

Upvotes: 0

AHungerArtist
AHungerArtist

Reputation: 9579

One way is to first convert it into a Date using SimpleDateFormat and its parse method (The javadoc will explain the format you need). Then you can look at the seconds and determine whether you should go up a minute or down (if it goes up, set the seconds to 0 and add a minute). Likewise for the hour, just look at minutes and if it's less than 30, round down and if greater than thirty set to zero and increase the hour.

Upvotes: 1

Related Questions