Parsing in time string in Java

2019-09-17 02:58发布

问题:

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.

回答1:

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



回答2:

The answer by Radyk is correct. Since the Question mentions ISO 8601 Duration, I will add that string output.

java.time

The java.time framework is built into Java 8 and later. Inspired by Joda-Time. Extended by the ThreeTen-Project. Brought to Java 6 & 7 by the ThreeTen-Backport project, and to Android by the ThreeTenABP project.

String durationAsLocalTimeString =  "00:10:10.0";
LocalTime durationAsLocalTime = LocalTime.parse( durationAsLocalTimeString );
Duration duration = Duration.between( LocalTime.MIN , durationAsLocalTime );
String output = duration.toString();

PT10M10S

ISO 8601 Duration Format

That output of PT10M10S is the standard Duration format of PnYnMnDTnHnMnS defined by ISO 8601. The P marks the beginning, the T separates the years-months-days portion from the hours-minutes-seconds portion.

I suggest serializing to strings in this format. Using time-of-day format such as 00:10:10.0 to represent an elapsed time is confusing and error-prone. The ISO 8601 format is obvious and intuitive and solves the ambiguity problem.

Both java.time and Joda-Time use these ISO 8601 formats by default when parsing/generating textual representations of date-time values.

Duration duration = Duration.parse( "PT10M10S" );


标签: java parsing