0

I am developing an application where I want to add hours. But I don't know how to do to take into account change of day for example. If I have

9:45 pm + 3:30

it should give

1:15 am

Thanks for help

Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
  • Which Java version? – Manuel Schmidt May 26 '17 at 17:49
  • It's AndroidStudio 2.3 in fact –  May 26 '17 at 17:51
  • 1
    Here is good example for you: https://stackoverflow.com/questions/21285161/android-difference-between-two-dates – Vasyl Lyashkevych May 26 '17 at 17:51
  • @VasylLyashkevych Thanks, I'll have a look at it soon and will tell you –  May 26 '17 at 17:53
  • Android - so assume Java 7 @ManuelSchmidt – weston May 26 '17 at 18:02
  • When you need to do date time arithmetic (as I call it) on Android, I recommend: Get the ThreeTenABP library. See [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). Look into the classes `LocalTime` and `Duration`. – Ole V.V. May 27 '17 at 09:03
  • This or similar has been covered many times on Stack Overflow. See [Adding n hours to a date in Java?](https://stackoverflow.com/questions/3581258/adding-n-hours-to-a-date-in-java) and [Add X hours to a date & time](https://stackoverflow.com/questions/23554801/add-x-hours-to-a-date-time) and more. Better to search before posting, it will often give you the answer faster. – Ole V.V. May 27 '17 at 09:11
  • Possible duplicate of [Add X hours to a date & time](https://stackoverflow.com/questions/23554801/add-x-hours-to-a-date-time) – Ole V.V. May 27 '17 at 09:11

4 Answers4

4
 String time = "2:00 pm";
 SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
 Date date = df.parse(time); 
 Calendar cal = Calendar.getInstance();
 cal.setTime(date);
 cal.add(Calendar.HOUR, 3);
 cal.add(Calendar.MINUTE, 30);
 int h = cal.get(Calendar.HOUR_OF_DAY);
 int m = cal.get(Calendar.MINUTE);

It will print 5:30 pm

EDIT: HOUR_OF_DAY provides a 24 h day

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
1
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;

class SumHours{

    public static void main(String[] args){

        DateFormat dateFormat = new SimpleDateFormat("h:mm a");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY,21);
        cal.set(Calendar.MINUTE,45);

        Date d = cal.getTime();
        System.out.println(dateFormat.format(d));

        cal.add(Calendar.HOUR, 3);
        cal.add(Calendar.MINUTE, 30);
        d = cal.getTime();

        System.out.println(dateFormat.format(d));
    }
}

Output:

9:45 PM
1:15 AM
1

Since so many have wanted to contribute an answer to this duplicate question (as I regard it), I thought it was time someone contributed the modern answer.

I know you are on Android Java 7, and until Java 8 comes to Android the modern answer requires you to use an external library, the ThreeTenABP. However, not only are the newer Java date and time classes in that library so much nicer to work with, when it comes to time arithmetic this is where they have one of their particularly strong points. So think about it, try it out. It’s also the future since the classes come built-in with Java 8 and later.

    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
    LocalTime startTime = LocalTime.of(21, 45);
    Duration hoursToAdd = Duration.ofHours(3).plusMinutes(30);
    LocalTime resultTime = startTime.plus(hoursToAdd);

    System.out.println("" + startTime.format(timeFormatter) + " + " + hoursToAdd 
            + " = " + resultTime.format(timeFormatter));

This prints:

9:45 PM + PT3H30M = 1:15 AM

I had wanted to give you lowercase pm and am and 3:30 as in your question. I admit we’re not quite there. In particular PT3H30M is peculiar if you haven’t learned ISO 8601 syntax. It means just 3 hours 30 minutes, easy enough when you know. Duration objects do not lend themselves well to formatting, it will help in Java 9, but as long as Java 8 hasn’t come to Android yet, let’s leave that. If you prefer lowercase pm, you may find the solution in this answer: displaying AM and PM in small letter after date formatting.

My code may not be that much shorter than the code in the other answers, but IMHO it is much easier to read.

Further links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    To format the `Duration` you can use `org.apache.commons.lang.time.DurationFormatUtils` from apache commons-lang (I use version **2.6**): `DurationFormatUtils.formatDuration(duration.toMillis(), "H:mm")` outputs `3:30` –  May 30 '17 at 19:27
0

Here is one of the decissions when you want to call this in anywhere:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeClass {

    static String timeStart24 = "21:45";
    static String timeStart = "09:45 PM";
    static String timeStep = "3:30";

    public String TimeClass(String start, String step) throws ParseException {
        // Take hours and minutes apart
        String[] time = step.split(":");
        // Create format of time
        SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
        SimpleDateFormat df24 = new SimpleDateFormat("HH:mm");
        // Input begining time
        Date from = df.parse(start);
        System.out.println(df.format(from));
        System.out.println(df24.format(from) + " - 24 hours format");

        // Create calendar instance
        Calendar cal = Calendar.getInstance();
        cal.setTime(from);
        // Inner method add of Calendar
        cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
        cal.add(Calendar.MINUTE, Integer.parseInt(time[1]));

        System.out.println(df.format(cal.getTime()));
//            System.out.print(df24.format(cal.getTime()));
        return df.format(cal.getTime());
    }

    public static void main(String[] args) throws ParseException {
        TimeClass tc = new TimeClass();
        tc.TimeClass(timeStart, timeStep);
    }

}

OUTPUT:

09:45 PM
21:45 - 24 hours format
01:15 AM
Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38