0

I would like to be able to turn a string like 1h 30m 12s into the milliseconds that the time would take. Like 1m would give me the long of 60000.

Is this possible?

toadless
  • 147
  • 10
  • Related and similar: [Java: How to convert a string (HH:MM:SS) to a duration?](https://stackoverflow.com/questions/8257641/java-how-to-convert-a-string-hhmmss-to-a-duration) There are more, please search. The one I link to even isn’t the most appropriate one. I will see if I can find a better one. – Ole V.V. Jun 05 '22 at 10:12
  • The one you linked formats it as "HH:MM:SS" and I want to format it differently like "10m 20s" – toadless Jun 05 '22 at 10:15
  • 1
    Yes, that’s why I said that it’s not the most appropriate one. It could be adapted, but we can do still better. `Duration.parse("PT" + "1h 30m 12s".replace(" ", "")).toMillis()` yields 5 412 000. You will want to break it up into more statements, of course. – Ole V.V. Jun 05 '22 at 10:39
  • I am searching in vain for the perfect match even though I swear it’s out there. [This one](https://stackoverflow.com/questions/61717336/how-can-i-get-time-format-from-user-input-in-java) is also similar but not quite to the point. – Ole V.V. Jun 05 '22 at 10:45
  • I'm with @OleV.V. - Duration is the best way to do this. His solution is even elegant enough to not force you into using the ISO format (PT1H30M12S). – Rob Spoor Jun 05 '22 at 10:45
  • [Spelling it out a bit here.](https://ideone.com/8xiRZb) Anyone feel free to include it in an answer. Also do consider keeping the `Duration` object around rather than converting to milliseconds. A `Duration` much better than an `int` or `long` conveys that this is a duration and hence makes your code clearer and more self-explanatory. – Ole V.V. Jun 05 '22 at 10:53
  • Thanks, @RobSpoor, I *am* converting to ISO 8601. Fortunately `Duration.parse()` tolerates lower case letters (don’t know whether that agrees with [the ISO 8601 standard](https://en.wikipedia.org/wiki/ISO_8601)). – Ole V.V. Jun 05 '22 at 10:59
  • 1
    [Maybe this link](https://stackoverflow.com/q/41785722/507738) – MC Emperor Jun 05 '22 at 11:11

0 Answers0