Parsing time strings like “1h 30min”

前端 未结 6 706
遇见更好的自我
遇见更好的自我 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:40

    Duration parsing is now included in Java 8. Use standard ISO 8601 format with Duration.parse.

    Duration d = Duration.parse("PT1H30M")
    

    You can convert this duration to the total length in milliseconds. Beware that Duration has a resolution of nanoseconds, so you may have data loss going from nanoseconds to milliseconds.

    long milliseconds = d.toMillis();
    

    The format is slightly different than what you describe but could be easily translated from one to another.

提交回复
热议问题