I almost finished the code, but still I need some help. This code calculates newTime based on adding minutes to startTime. The minutes might have values greater than 60. The problem is that in the current example it must output “00:10”, but it outputs “23:70″…
String startTime = "23:40";
int minutes = 30;
String[] hm = startTime.split(":");
int h = minutes / 60 + Integer.parseInt(hm[0]);
int m = minutes % 60 + Integer.parseInt(hm[1]);
if (m<0) {
if (h==0)
h=23;
else
h = h-1;
m = 60+m;
}
String newTime = String.format("%02d", h)+":"+String.format("%02d", m);
System.out.println(newTime);
I suggest calculating the total number of minutes since midnight as a single value, then adding the desired amount, and then recalculating the resulting hours and minutes:
You absolutely should not be adding your
minutesvariable to the calculation ofh– they’re incompatible units.