如何在Java中转换Youtube API V3持续时间 [英] How to convert Youtube API V3 duration in Java

查看:127
本文介绍了如何在Java中转换Youtube API V3持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Youtube V3 API使用ISO8601时间格式来描述视频的时长. 像"PT1M13S"之类的东西.现在,我想将字符串转换为秒数(例如本例中为73).

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 example 73 in this case).

有没有Java库可以帮助我轻松地在Java 6下完成任务? 还是我必须自己完成正则表达式任务?

Is there any Java library can help me easily do the task under Java 6? Or I have to do the regex task by myself?

修改

最后,我接受@Joachim Sauer的回答

Finally I accept the answer from @Joachim Sauer

带有Joda的示例代码如下.

PeriodFormatter formatter = ISOPeriodFormat.standard();
Period p = formatter.parsePeriod("PT1H1M13S");
Seconds s = p.toStandardSeconds();

System.out.println(s.getSeconds());

推荐答案

Joda时间是转到库,可以处理任何类型的与时间相关的功能.

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

对于这种特定情况 ISOPeriodFormat.standard()返回 PeriodFormatter 可以解析和格式化该格式.

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

结果对象为 a Period (

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).

编辑:给我未来的一封信:这个答案已经有好几年了. Java 8带来了java.time.Duration,它也可以解析这种格式,并且不需要外部库.

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.

这篇关于如何在Java中转换Youtube API V3持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆