I've got a REST service that I use in my Android app that gives me a time, time only, but it returns also something like
"24:38:00"
or "25:15:00"
so, what I need is to parse this time and put a real result out in 24h format. It should be
"00:38:00"
and "01:15:00"
I tried use this way
LocalTime localTime = new LocalTime(timeModel.getTimeString());
but i have this error now Cannot parse "24:38:00": Value 24 for hourOfDay must be in the range [0,23]
How can I solve? I need only the time not date
In this case you could assume that these time Strings are not following any rules, because if 24
and 25
exist as values for the "hour" part, why wouldn't they reply with 37
?
You can use this to clean this up:
private static String modifyTimeString(String s) {
//the hour might only be 1 digit, so "the first 2 chars" is not a safe approach
int colonIndex = s.indexOf(':');
String hoursString = s.substring(0, colonIndex);
Integer hours = Integer.valueOf(hoursString);
if(hours < 24) {
return s;
}
/*while(hours >= 24) {
hours -= 24;
}*/
//smarter, see ronos answer:
hours = hours % 24;
//put a leading 0 in there for single-digit-hours
hoursString = hours.toString();
if(hours<10) {
hoursString = "0" + hoursString;
}
return hoursString + s.substring(colonIndex);
}
Calling modifyTimeString("25:15:00")
returns "01:15:00"