2

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
  • 262,936
  • 84
  • 758
  • 1,028
subodh
  • 6,004
  • 12
  • 48
  • 69

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
  • 262,936
  • 84
  • 758
  • 1,028
  • 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