java中的Json持续时间格式问题

时间:2014-09-04 12:27:45

标签: java android json

我有什么方法可以将这种格式2640 Hrs : 00 Mts转换为14:22:57 hrs

我尝试了很多方法,似乎没有任何工作。我真的需要帮助。

Json Array

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

我试过的代码

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

以上代码抛出此异常

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

我正在使用 Volley GsonRequest 并且我能够解析它但无法格式化时间。

1 个答案:

答案 0 :(得分:1)

对我来说,这不是一个已知的时间格式,并且没有"标准化",这意味着它给你2642小时,这不适合24小时制。

所以我会选择手动解析,例如:

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));

我没有测试过这段代码,所以YMMV,但你应该明白这个想法。