Reputation: 27
I have an app where i need to check if travel is in duration between 4 hours and 30 hours, I store it as a strings "04:00" and "30:00", then i try to parse it using LocalTime.parse()
, "04:00" is parsed successfully but "30:00" gets an error for invalid format, what could be best way to parse duration hours from a string ?
Upvotes: 2
Views: 4529
Reputation: 1163
First of all, you're storing it somehow wrong. I suggest to store it in way Duration.parse
can handle it, in standard ISO 8601 format.
Examples:
"PT20.345S" -- parses as "20.345 seconds"
"PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
"PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)
"P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
"P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
"P-6H3M" -- parses as "-6 hours and +3 minutes"
"-P6H3M" -- parses as "-6 hours and -3 minutes"
"-P-6H+3M" -- parses as "+6 hours and -3 minutes"
So then you can just do:
Duration dur30H = Duration.parse("PT30H"); // 30h
Duration dur4H = Duration.parse("PT4H"); // 4h
Duration travelTime = Duration.parse("P1D"); // 1D
boolean result = travelTime.compareTo(dur30H) <= 0 && travelTime.compareTo(dur4H) >= 0; // true
Upvotes: 7