用Java解析时间字符串 [英] Parsing in time string in Java
问题描述
我有一个规范,该规范将在成功交易后返回付款历史记录JSON.第三方JSON响应具有一个字段,表示该事务花费的总时间.例如,执行付款历史记录时花费的总时间为"00:10:10.0".如何将此String对象的这种格式转换为整数基元.
I have a specification which would return the payment history JSON after successful transaction. 3rd party JSON response has a field for the total time taken for the transaction. As example total time spent while doing the payment history was "00:10:10.0". How do I convert this format this String object to integer primitive.
推荐答案
If you don't mind using external library, then using Joda's org.joda.time.LocalTime
can help with the string parsing:
String duration = "00:10:10.0";
int seconds = LocalTime.parse(duration).getMillisOfDay() / 1000;
//returns 610
请注意,由于您遵循ISO格式,因此甚至无需显式指定解析的格式.
此外,如果您已经在使用Java 8,则将Joda用作那里可用的新日期/时间库的启发,因此您将在标准库中找到一个类似的类:
Also, if you're using Java 8 already, than Joda was used as an inspiration for the new date/time library available there, therefore you'll find a similar class in the standard library: LocalTime
这篇关于用Java解析时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!