Parsing time strings like “1h 30min”

前端 未结 6 707
遇见更好的自我
遇见更好的自我 2020-11-29 07:28

Anyone know of a Java library that can parse time strings such as \"30min\" or \"2h 15min\" or \"2d 15h 30min\" as milliseconds (or some kind of Duration object). Can Joda-T

6条回答
  •  独厮守ぢ
    2020-11-29 07:54

    You'll probably have to tweak this a bit for your own format, but try something along these lines:

    PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendDays().appendSuffix("d ")
        .appendHours().appendSuffix("h ")
        .appendMinutes().appendSuffix("min")
        .toFormatter();
    
    Period p = formatter.parsePeriod("2d 5h 30min");
    

    note that there is a appendSuffix that takes a variants parameter if you need to make it more flexible.

    Update: Joda Time has since added Period.toStandardDuration(), and from there you can use getStandardSeconds() to get the elapsed time in seconds as a long.

    If you're using an older version without these methods you can still calculate a timestamp yourself by assuming the standard 24/hr in a day, 60min/hr, etc. (In this case, take advantage of the constants in the DateTimeConstants class to avoid the need for magic numbers.)

提交回复
热议问题