How to convert Youtube API V3 duration in Java

前端 未结 15 2003
梦如初夏
梦如初夏 2021-02-07 03:39

The Youtube V3 API uses ISO8601 time format to describe the duration of videos. Something likes \"PT1M13S\". And now I want to convert the string to the number of seconds (for

15条回答
  •  暖寄归人
    2021-02-07 04:08

    Joda Time is the go-to library for time-related functions of any kind.

    For this specific case ISOPeriodFormat.standard() returns a PeriodFormatter that can parse and format that format.

    The resulting object is a Period (JavaDoc). Getting the actual number of seconds would then be period.toStandardSeconds().getSeconds(), but I suggest you just handle the duration as a Period object (for ease of handling and for type safety).

    Edit: a note from future me: this answer is several years old now. Java 8 brought java.time.Duration along which can also parse this format and doesn't require an external library.

提交回复
热议问题