Java : how to add 10 mins in my Time

前端 未结 8 1801
闹比i
闹比i 2020-11-27 21:00

I am getting this time

String myTime = \"14:10\";

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

相关标签:
8条回答
  • 2020-11-27 21:09

    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.

    0 讨论(0)
  • 2020-11-27 21:14

    Java 7 Time API

        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
    
        LocalTime lt = LocalTime.parse("14:10");
        System.out.println(df.format(lt.plusMinutes(10)));
    
    0 讨论(0)
  • 2020-11-27 21:17

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

    0 讨论(0)
  • 2020-11-27 21:19

    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())));
    
    0 讨论(0)
  • 2020-11-27 21:22

    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.

    0 讨论(0)
  • 2020-11-27 21:23

    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.

    0 讨论(0)
提交回复
热议问题