Java : how to add 10 mins in my Time

前端 未结 8 1802
闹比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:26

    Something like this

     String myTime = "14:10";
     SimpleDateFormat df = new SimpleDateFormat("HH:mm");
     Date d = df.parse(myTime); 
     Calendar cal = Calendar.getInstance();
     cal.setTime(d);
     cal.add(Calendar.MINUTE, 10);
     String newTime = df.format(cal.getTime());
    

    As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.

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

    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
    
    0 讨论(0)
提交回复
热议问题