如何读取从 Youtube 返回的视频的时长 API Kotlin/Java

How to read the duration of a video returned from Youtube API Kotlin/Java

我基本上想将此 ISO 格式 PT18M8S 转换为 13:0910000ms 之类的格式 我从 YouTube Data API v3:

中获取这种格式

您可以使用 java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementationJava-9 引入了一些更方便的方法。

如果您浏览了上述链接,您可能已经注意到 PT18M8S 指定了 18 分 8 秒的持续时间,您可以将其解析为 Duration 对象并从该对象中解析出来,您可以通过从中获取天数、小时数、分钟数、秒数来创建根据您的要求格式化的字符串。

演示:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        String strIso8601Duration = "PT18M8S";

        Duration duration = Duration.parse(strIso8601Duration);
        // Default format
        System.out.println(duration);

        // Custom format
        // ####################################Java-8####################################
        String formattedElapsedTime = String.format("%02d:%02d:%02d", duration.toHours() % 24,
                duration.toMinutes() % 60, duration.toSeconds() % 60);
        System.out.println(formattedElapsedTime);
        // ##############################################################################

        // ####################################Java-9####################################
        formattedElapsedTime = String.format("%02d:%02d:%02d", duration.toHoursPart(), duration.toMinutesPart(),
                duration.toSecondsPart());
        System.out.println(formattedElapsedTime);
        // ##############################################################################

        System.out.println(duration.toMillis() + " milliseconds");
    }
}

输出:

PT18M8S
00:18:08
00:18:08
1088000 milliseconds

Trail: Date Time.

了解现代日期时间 API
  • 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它向后移植了大部分 java.time Java 6 和 7 的功能。
  • 如果您正在为 Android 项目工作,并且您的 Android API 水平仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring and
    object YouTubeDurationConverter {
    
        private fun getHours(time: String): Int {
            return time.substring(time.indexOf("T") + 1, time.indexOf("H")).toInt()
        }
    
        private fun getMinutes(time: String): Int {
            return time.substring(time.indexOf("H") + 1, time.indexOf("M")).toInt()
        }
    
        private fun getMinutesWithNoHours(time: String): Int {
            return time.substring(time.indexOf("T") + 1, time.indexOf("M")).toInt()
        }
    
        private fun getMinutesWithNoHoursAndNoSeconds(time: String): Int {
            return time.substring(time.indexOf("T") + 1, time.indexOf("M")).toInt()
        }
    
        private fun getSecondsOnly(time: String): Int {
            return time.substring(time.indexOf("T") + 1, time.indexOf("S")).toInt()
        }
    
        private fun getSecondsWithMinutes(time: String): Int {
            return time.substring(time.indexOf("M") + 1, time.indexOf("S")).toInt()
        }
    
        private fun getSecondsWithHours(time: String): Int {
            return time.substring(time.indexOf("H") + 1, time.indexOf("S")).toInt()
        }
    
        private fun convertToFormatedTime(time: String): FormatedTime {
    
            val HOURS_CONDITION = time.contains("H")
            val MINUTES_CONDITION = time.contains("M")
            val SECONDS_CONDITION = time.contains("S")
    
            /**
             *potential cases
             *hours only
             *minutes only
             *seconds only
             *hours and minutes
             *hours and seconds
             *hours and minutes and seconds
             *minutes and seconds
             */
            val formatTime = FormatedTime(-1, -1, -1)
    
            if (time.equals("P0D")) {
                //Live Video
                return formatTime
            } else {
                var hours = -1
                var minutes = -1
                var seconds = -1
    
                if (HOURS_CONDITION && !MINUTES_CONDITION && !SECONDS_CONDITION) {
                    //hours only
                    hours = getHours(time)
                } else if (!HOURS_CONDITION && MINUTES_CONDITION && !SECONDS_CONDITION) {
                    //minutes only
                    minutes = getMinutesWithNoHoursAndNoSeconds(time)
    
                } else if (!HOURS_CONDITION && !MINUTES_CONDITION && SECONDS_CONDITION) {
                    //seconds only
                    seconds = getSecondsOnly(time)
    
    
                } else if (HOURS_CONDITION && MINUTES_CONDITION && !SECONDS_CONDITION) {
                    //hours and minutes
                    hours = getHours(time)
                    minutes = getMinutes(time)
    
                } else if (HOURS_CONDITION && !MINUTES_CONDITION && SECONDS_CONDITION) {
                    //hours and seconds
                    hours = getHours(time)
                    seconds = getSecondsWithHours(time)
    
    
                } else if (HOURS_CONDITION && MINUTES_CONDITION && SECONDS_CONDITION) {
                    //hours and minutes and seconds
                    hours = getHours(time)
                    minutes = getMinutes(time)
                    seconds = getSecondsWithMinutes(time)
    
    
                } else if (!HOURS_CONDITION && MINUTES_CONDITION && SECONDS_CONDITION) {
                    //minutes and seconds
                    minutes = getMinutesWithNoHours(time)
                    seconds = getSecondsWithMinutes(time)
    
                }
                return FormatedTime(hours, minutes, seconds)
            }
        }
    
        fun getTimeInStringFormated(time: String): String {
            val formatedTime = convertToFormatedTime(time)
            val timeFormate: StringBuilder = StringBuilder("")
    
            if (formatedTime.hour == -1) {
                timeFormate.append("00:")
            } else if (formatedTime.hour.toString().length == 1) {
                timeFormate.append("0" + (formatedTime.hour).toString() + ":")
            } else {
                timeFormate.append((formatedTime.hour).toString() + ":")
            }
            if (formatedTime.minutes == -1) {
                timeFormate.append("00:")
            } else if (formatedTime.minutes.toString().length == 1) {
                timeFormate.append("0" + (formatedTime.minutes).toString() + ":")
            } else {
                timeFormate.append((formatedTime.minutes).toString() + ":")
            }
    
            if (formatedTime.second == -1) {
                timeFormate.append("00")
            } else if (formatedTime.second.toString().length == 1) {
                timeFormate.append("0" + (formatedTime.second).toString())
            } else {
                timeFormate.append(formatedTime.second)
            }
            return timeFormate.toString()
        }
    
        fun getTimeInSeconds(time: String): Int {
    
            val formatedTime = convertToFormatedTime(time)
            var tottalTimeInSeconds = 0
            if (formatedTime.hour != -1) {
                tottalTimeInSeconds += (formatedTime.hour * 60 * 60)
            }
            if (formatedTime.minutes != -1) {
                tottalTimeInSeconds += (formatedTime.minutes * 60)
            }
            if (formatedTime.second != -1) {
                tottalTimeInSeconds += (formatedTime.second)
    
            }
            return tottalTimeInSeconds
        }
        fun getTimeInMillis(time: String):Long
        {
            val timeInSeconds = getTimeInSeconds(time)
            return (timeInSeconds*1000).toLong()
        }}
    
    
    data class FormatedTime (var hour:Int,var minutes:Int,var second:Int)
    
     
    Output Sample
    1.getTimeInStringFormated: 11:54:48
2.getTimeInSeconds: 42888
3.getTimeInMillis: 42888000