Gurupriyan
Gurupriyan

Reputation: 51

Json time duration formatting issue in java

Is there any way that I could convert time in this format 2640 Hrs : 00 Mts to 14:22:57 hrs.

I tried a lot of ways and nothing seems to be working. I really need help.

Json Array

{"ElapsedTime":"2642 Hrs : 59 Mts"}

Code I tried

DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
Date date = dateFormat.parse(jsonDate);
return dateFormat.format(date);

The above code throws this exception

java.text.ParseException: Unparseable date: "2640 Hrs : 00 Mts" (at offset 4)

I'm using Volley GsonRequest and I'm able to parse it but unable to format time.

Upvotes: 0

Views: 639

Answers (1)

Simone Gianni
Simone Gianni

Reputation: 11672

To me that is not a known time format, and is not "normalized", meaning it gives you 2642 hours, that doesn't fit into a 24 hours clock.

So I would go with manual parsing, something like :

Pattern pattern = Pattern.compile("([0-9]*) Hrs : ([0-9]*) Mts");
Matcher matcher = pattern.matcher(jsonString);
int hours = Integer.parseInt(matcher.group(1));
int minutes = Integer.parseInt(matcher.group(2));
long time = (hours * 60) + minutes; // In minutes
time *= 60000; // In milliseconds
return dateFormat.format(new Date(time));

I have not tested this code, so YMMV, but you should get the idea.

Upvotes: 1

Related Questions