Parsing duration string into milliseconds

前端 未结 3 529
庸人自扰
庸人自扰 2021-01-02 15:22

I need to parse a duration string, of the form 98d 01h 23m 45s into milliseconds.

I was hoping there was an equivalent of SimpleDateFormat

3条回答
  •  孤独总比滥情好
    2021-01-02 15:58

    Check out PeriodFormatter and PeriodParser from JodaTime library.

    You can also use PeriodFormatterBuilder to build a parser for your strings like this

    String periodString = "98d 01h 23m 45s";
    
    PeriodParser parser = new PeriodFormatterBuilder()
       .appendDays().appendSuffix("d ")
       .appendHours().appendSuffix("h ")
       .appendMinutes().appendSuffix("m ")
       .appendSeconds().appendSuffix("s ")
       .toParser();
    
    MutablePeriod period = new MutablePeriod();
    parser.parseInto(period, periodString, 0, Locale.getDefault());
    
    long millis = period.toDurationFrom(new DateTime(0)).getMillis();
    

    Now, all this (especially the toDurationFrom(...) part) may look tricky, but I really advice you to look into JodaTime if you're dealing with periods and durations in Java.

    Also look at this answer about obtaining milliseconds from JodaTime period for additional clarification.

提交回复
热议问题