I googled but not able to find any good solution which will validate the input string is correct for ISO Duration Format, if any one has any idea or solution may be using regexp or function, will help a lot.
Note: The format for a duration is [-]P[n]DT[n]H[n]M[n][.frac_secs]S where n specifies the value of the element (for example, 4H is 4 hours). This represents a subset of the ISO duration format and any other duration letters (including valid ISO letters such as Y and M) result in an error.
Example 1,
input string = "P100DT4H23M59S";
expected output = 100 04:23:59.000000
Example 2,
input string = "P2MT12H";
expected output = error, because the month designator, '2M', isn't allowed.
Example 3,
input string = "100 04:23:59";
expected output = 100 04:23:59.000000
.
java.time.DurationThe java.time classes use ISO 8601 formats by default when parsing/generating text.
Use the Duration class.
Call Duration#parse method. Trap for DateTimeParseException being thrown when encountering faulty input.
String input = "P100DT4H23M59S";
try
{
Duration duration = Duration.parse( input );
}
catch ( DateTimeParseException e )
{
System.out.println( "ERROR - Faulty input." );
}
The Duration class in Java represents a span-of-time unattached to the timeline on the scale of generic 24-hour days (not calendar days), hours, minutes, and seconds. (For calendar days, see Period class.)
So your undesired inputs of years, months, and weeks are automatically rejected by Duration#parse.
String input = "P2MT12H";
try
{
Duration duration = Duration.parse( input );
}
catch ( DateTimeParseException e )
{
System.out.println( "ERROR - Faulty input." );
}
When run:
ERROR - Faulty input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With