Skip to content
Advertisement

How to Convert DurationFormatUtils back to Milliseconds

Currently I have been using DurationFormatUtils to convert the Millis in a track into HH:mm:ss, but I want to allow the user to seek the track using this format, for example they would type: ‘-seek HH:mm:ss or mm:ss’ and I want to convert that time back into milliseconds… Are there any built in Java methods to do this? Or would I have to create my own method to convert it?

Advertisement

Answer

You can do it like this.

First, define a DateTimeFormatter instance.

JavaScript
  • H – one or two digits of 24 hour time
  • mm – minutes
  • ss – seconds

To handle absence of the hours you can check to see if a colon exists from the 3rd character on. If it does, then the time can be parsed as is, otherwise, prepend 00 hours. I chose to put it in a lambda.

JavaScript

Putting it all together.

JavaScript

prints

JavaScript

Check out the java.time package for more date/time classes.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement