gpt4 book ai didi

java - 将 Youtube Data API V3 视频持续时间转换为 hh :mm:ss format in java?

转载 作者:行者123 更新时间:2023-12-02 07:47:35 24 4
gpt4 key购买 nike

我正在使用 Youtube data api v3 获取视频信息,例如标题、观看次数和持续时间。持续时间值对我来说是新的,因为它是一个 ISO8601 日期,我需要将其转换为可读格式就像 hh:mm:ss。持续时间可以有以下不同的值:

  1. PT1S --> 00:01
  2. PT1M --> 01:00
  3. PT1H --> 01:00:00
  4. PT1M1S --> 01:01
  5. PT1H1S --> 01:00:01
  6. PT1H1M1S --> 01:01:01

我可以使用Joda Time library解析该值并计算持续时间(以秒为单位),但该库的大小为 500kb,这会增加我不想要的应用程序的大小。

最佳答案

看看这段代码:

private static HashMap<String, String> regexMap = new HashMap<>();
private static String regex2two = "(?<=[^\\d])(\\d)(?=[^\\d])";
private static String two = "0$1";

public static void main(String[] args) {

regexMap.put("PT(\\d\\d)S", "00:$1");
regexMap.put("PT(\\d\\d)M", "$1:00");
regexMap.put("PT(\\d\\d)H", "$1:00:00");
regexMap.put("PT(\\d\\d)M(\\d\\d)S", "$1:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)S", "$1:00:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)M", "$1:$2:00");
regexMap.put("PT(\\d\\d)H(\\d\\d)M(\\d\\d)S", "$1:$2:$3");

String[] dates = { "PT1S", "PT1M", "PT1H", "PT1M1S", "PT1H1S", "PT1H1M", "PT1H1M1S", "PT10H1M13S", "PT10H1S", "PT1M11S" };

for (String date : dates) {
String d = date.replaceAll(regex2two, two);
String regex = getRegex(d);
if (regex == null) {
System.out.println(d + ": invalid");
continue;
}
String newDate = d.replaceAll(regex, regexMap.get(regex));
System.out.println(date + " : " +newDate);
}
}

private static String getRegex(String date) {
for (String r : regexMap.keySet())
if (Pattern.matches(r, date))
return r;
return null;
}

regex2two 用于向 1 位数字添加前导零0。你可以试试这个demo .

regexMap 中,我存储了所有 7 个案例和适当的正则表达式替换。

关于java - 将 Youtube Data API V3 视频持续时间转换为 hh :mm:ss format in java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24078662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com