Ansh
Ansh

Reputation: 2396

Converting Youtube Data API V3 video duration to hh:mm:ss format in java?

I am using Youtube data api v3 to get video information like title, views count and duration.The duration value is new to me as it's an ISO8601 date which I need to convert to a readable format like hh:mm:ss. Duration can have the following different values:

  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

I could use Joda Time library to parse the value and calculate the duration in seconds but the library is of 500kb in size which will increase the size of my application that I don't want.

Upvotes: 2

Views: 3251

Answers (4)

Farvardin
Farvardin

Reputation: 5424

look at this code :

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

The regex2two has been used to add a leading zero0 to 1-digit numbers. you can try this demo.

In the regexMap I'v stored all 7 cases and appropriate regex-replace.

Upvotes: 5

MrSoloDolo
MrSoloDolo

Reputation: 406

I needed a array of all these converted duration. So I wrote the below as a workaround and also java.time.duration was not working for me, don't know why.

String[] D_uration = new String[10];
while(iteratorSearchResults.hasNext()){String Apiduration1=Apiduration.replace("PT","");
                            if(Apiduration.indexOf("H")>=0){
                                String Apiduration2=Apiduration1.replace("H",":");
                                if(Apiduration.indexOf("M")>=0){
                                    String Apiduration3=Apiduration2.replace("M",":");
                                    if(Apiduration.indexOf("S")>=0){
                                        D_uration[i]=Apiduration3.replace("S","");


                                    }
                                    else{
                                        String Apiduration4=Apiduration2.replace("M",":00");
                                        D_uration[i]=Apiduration4;
                                    }
                                }
                                else{
                                    String Apiduration4=Apiduration2.replace(":",":00:");
                                    if(Apiduration.indexOf("S")>=0){
                                        D_uration[i]=Apiduration4.replace("S","");


                                    }
                                    else{
                                        String Apiduration3=Apiduration4.replace(":00:",":00:00");
                                        D_uration[i]=Apiduration3;
                                    }
                                }
                            }
                            else{

                                if(Apiduration.indexOf("M")>=0){
                                    String Apiduration2=Apiduration1.replace("M",":");
                                    if(Apiduration.indexOf("S")>=0){
                                        D_uration[i]=Apiduration2.replace("S","");


                                    }
                                    else{
                                        String Apiduration4=Apiduration2.replace(":",":00");
                                        D_uration[i]=Apiduration4;
                                    }

                                }
                                else{

                                    D_uration[i]=Apiduration1.replace("S","");




                                }
                            }

"Apiduration" is returned by the Youtube data Api in ISO8601 format.

Made some edits now i think it should work fine.

Upvotes: 0

sonida
sonida

Reputation: 4411

I did by myself

Let's try

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.

public class YouTubeDurationUtils {
    /**
     * 
     * @param duration
     * @return "01:02:30"
     */
    public static String convertYouTubeDuration(String duration) {
        String youtubeDuration = duration; //"PT1H2M30S"; // "PT1M13S";
        Calendar c = new GregorianCalendar();
        try {
            DateFormat df = new SimpleDateFormat("'PT'mm'M'ss'S'");
            Date d = df.parse(youtubeDuration);
            c.setTime(d);
        } catch (ParseException e) {
            try {
                DateFormat df = new SimpleDateFormat("'PT'hh'H'mm'M'ss'S'");
                Date d = df.parse(youtubeDuration);
                c.setTime(d);
            } catch (ParseException e1) {
                try {
                    DateFormat df = new SimpleDateFormat("'PT'ss'S'");
                    Date d = df.parse(youtubeDuration);
                    c.setTime(d);
                } catch (ParseException e2) {
                }
            }
        }
        c.setTimeZone(TimeZone.getDefault());

        String time = "";
        if ( c.get(Calendar.HOUR) > 0 ) {
            if ( String.valueOf(c.get(Calendar.HOUR)).length() == 1 ) {
                time += "0" + c.get(Calendar.HOUR);
            }
            else {
                time += c.get(Calendar.HOUR);
            }
            time += ":";
        }
        // test minute
        if ( String.valueOf(c.get(Calendar.MINUTE)).length() == 1 ) {
            time += "0" + c.get(Calendar.MINUTE);
        }
        else {
            time += c.get(Calendar.MINUTE);
        }
        time += ":";
        // test second
        if ( String.valueOf(c.get(Calendar.SECOND)).length() == 1 ) {
            time += "0" + c.get(Calendar.SECOND);
        }
        else {
            time += c.get(Calendar.SECOND);
        }
        return time ;
    }
}

Upvotes: 4

a.scarlett
a.scarlett

Reputation: 77

Had to deal with this problem as well. I had to convert the length to milliseconds, but once you get the secs/mins/hours variables populated you can convert to any format you want:

// Test Value
$vidLength = 'PT1H23M45S';

$secs = '';
$mins = '';
$hours = '';
$inspecting = '';
for($i=(strlen($vidLength)-1); $i>0; $i--){
    if(is_numeric($vidLength[$i])){
        if($inspecting == 'S'){
            $secs = $vidLength[$i].$secs;
        }
        else if($inspecting == 'M'){
            $mins = $vidLength[$i].$mins;
        }
        else if($inspecting == 'H'){
            $hours = $vidLength[$i].$hours;
        }
    }
    else {
        $inspecting = $vidLength[$i];
    }
}

$lengthInMS = 1000*(($hours*60*60) + ($mins*60) + $secs); 

Upvotes: 1

Related Questions