tl;dr
Duration.parse( "PT2H30M" )
ISO 8601
If you are willing to redefine your desired input formats, I suggest using the already-existing formats defined by the ISO 8601 standard.
The pattern PnYnMnDTnHnMnS
uses a P
to mark the beginning, a T
to separate any years-months-days portion from any hours-minutes-seconds portion.
An hour-and-a-half is PT1H30M
, for example.
java.time
The java.time classes use the ISO 8601 formats by default when parsing/generating strings. This includes the Period
and Duration
classes for representing spans of time not attached to the timeline.
Duration d = Duration.ofHours( 1 ).plusMinutes( 30 );
String output = d.toString();
Going the other direction, parsing a string.
Duration d = Duration.parse( "PT1H30M" );
See live code in IdeOne.com.
See my similar Answer to a similar Question.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
6h 42m
, and that results inUnparseable date: "6h 42m"
, so I am still stuck. This only works when the user enters something like6:42:00 AM
, which doesn't work for me since the intent is to enter a time duration. – Gaines