Search code examples
javamethodsformatting

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?


Solution

  • You can do it like this.

    First, define a DateTimeFormatter instance.

    DateTimeFormatter dtf =
            DateTimeFormatter.ofPattern("H:mm:ss");
    
    • 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.

    Function<String,String> adjust = time -> time.indexOf(":",3) >= 0 
                ? time : "00:"+time;
    

    Putting it all together.

    String[] times = { "3:49:44", "12:30" };
    for (String time : times) {
        int millis = dtf.parse(adjust.apply(time))
              .get(ChronoField.MILLI_OF_DAY);
        System.out.println(millis);
    }
    

    prints

    13784000
    750000
    

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