3

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

.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
subodh
  • 6,136
  • 12
  • 51
  • 73

1 Answers1

2

java.time.Duration

The 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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • This is the recommended way to do it in production code. **A note for the OP and other future visitors**: Do not use a regex (as suggested in the comments) as the solution to this problem, in production. However, you can try regex as the solution to this problem for learning and fun. – Arvind Kumar Avinash Dec 29 '20 at 20:21
  • Isn't `PT25H` an invalid value? In the code this value is being parsed without any error message – firstpostcommenter Aug 05 '22 at 17:54
  • 1
    @firstpostcommenter No, nothing wrong with an input of 25 hours. In a `Duration` that means one 24-hour day and one hour. A `Duration` represents a span of time in terms of hours-minutes-seconds-nanoseconds. I don’t know the maximum, but you can have [at least two billion hours](https://ideone.com/Nfs765). – Basil Bourque Aug 05 '22 at 21:03