[java] How to add 10 minutes to my (String) time?

I have this time:

String myTime = "14:10";

Now I want to add 10 minutes to this time, so that it would be 14:20

How can I achieve this?

This question is related to java

The answer is


I used the code below to add a certain time interval to the current time.

    int interval = 30;  
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Calendar time = Calendar.getInstance();

    Log.i("Time ", String.valueOf(df.format(time.getTime())));

    time.add(Calendar.MINUTE, interval);

    Log.i("New Time ", String.valueOf(df.format(time.getTime())));

You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.

String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());

Output :

14:10
14:20

Java 7 Time API

    DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");

    LocalTime lt = LocalTime.parse("14:10");
    System.out.println(df.format(lt.plusMinutes(10)));

Use Calendar.add(int field,int amount) method.


I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.


I would use Joda Time, parse the time as a LocalTime, and then use

time = time.plusMinutes(10);

Short but complete program to demonstrate this:

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
        LocalTime time = formatter.parseLocalTime("14:10");
        time = time.plusMinutes(10);
        System.out.println(formatter.print(time));
    }       
}

Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.


You need to have it converted to a Date, where you can then add a number of seconds, and convert it back to a string.