Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 791
Ansh Avatar asked Mar 26 '26 05:03

Ansh


1 Answers

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.

like image 112
Taher Khorshidi Avatar answered Mar 28 '26 17:03

Taher Khorshidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!