Karim Sinouh
Karim Sinouh

Reputation: 1682

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

I basically want to convert this ISO format PT18M8S to something like 13:09 or 10000ms I'm getting this format from YouTube Data API v3:

Picture of the JSON returned

Upvotes: 0

Views: 954

Answers (2)

abdelrhman elgendy
abdelrhman elgendy

Reputation: 11

    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

Upvotes: 1

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.

If you have gone through the above links, you might have already noticed that PT18M8S specifies a duration of 18 minutes 8 seconds that you can parse to a Duration object and out of this object, you can create a string formatted as per your requirement by getting days, hours, minutes, seconds from it.

Demo:

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");
    }
}

Output:

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

Learn about the modern date-time API from Trail: Date Time.

Upvotes: 3

Related Questions