天天看點

java 解析時間字元串,用Java解析時間字元串

java 解析時間字元串,用Java解析時間字元串

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

Please note, that since you're complying to ISO formatting you don't even need to explicitly specify the parsed format.

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