0

I have an initial time 12:00:00 and I need to add 144 mins to it.

The expected output is 15.24.00 (i.e, adding 2.24 hours to the initial time).

How should I update the current code given below ?

String startTime = "13:00:00";
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date date1 = null;
Date date2 = null;  
try {
    date1 = format.parse(startTime);    
} catch (ParseException e) {
    e.printStackTrace();    
}
Long addition = (long) (TimeUnit.MILLISECONDS.toMinutes(date1.getTime()));
System.out.println("Difference : "+addition);
Anish B.
  • 9,111
  • 3
  • 21
  • 41
  • 2
    Any reason you can't use the `java.time` APIs (Java 8+) or the ThreeTenBackPort libraries (Java 7-) – MadProgrammer Jan 28 '20 at 09:58
  • 2
    Does this answer your question? [Java : how to add 10 mins in my Time](https://stackoverflow.com/questions/9015536/java-how-to-add-10-mins-in-my-time) – Sagun Raj Lage Jan 28 '20 at 11:31

3 Answers3

5

You should use a modern date-time API as follows :

import java.time.Duration;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalTime time = LocalTime.parse("13:00:00").plus(Duration.ofMinutes(144));
        System.out.println(time);
    }
}

Output:

15:24

Check here for more information.

Anish B.
  • 9,111
  • 3
  • 21
  • 41
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Step 1:

Convert input String to java.util.Date via implementing the following logic:

public static Date getDate(String source, String format) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat(format);
    return dateFormat.parse(source);
}

Step 2:

Adding minutes to the date:

    public static Date add(Date date, int minute) {
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(date);
       calendar.add(Calendar.MINUTE, minute);
       return calendar.getTime();
    }

Step 3:

Now, If you want to convert java.util.Date back to String use following logic:

    public static String getDate(Date date, String format) {
       DateFormat dateFormat = new SimpleDateFormat(format);
       return dateFormat.format(date);
    }
Punit Tiwari
  • 496
  • 4
  • 8
0

You can do it in the below way:

String str = "13:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("kk:mm:ss");
LocalTime dateTime = LocalTime.parse(str, formatter).plusMinutes(144);
System.out.println(dateTime);
Anuradha
  • 570
  • 6
  • 20