Search code examples
dartyoutube-data-api

How Can Parse Youtube Duration to Date?


I can't parse Youtube duration to date or date time, I search and visit many web site but I can't parse youtube string duration

Youtube duration sample is : PT15M33S

Please click for youtube api documentation


Solution

  • It's ISO 8601 durations are given in the format P[n]Y[n]M[n]DT[n]H[n]M[n]S

    Examples:

    20 seconds:

    PT20.0S
    

    One year, 3 month, 3 days, 4 hours, 5 minutes, 10 seconds:

    P1Y3M3DT4H5M10S
    

    Unfortunately, dart does not give parser api Duration class So you have to parser your own and feed into Duration and convert to Datatime

    You can try Match-class

    String durationString = "P2Y5M3W4DT5H4M2S";
    String regxPattern= "^P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(T(\\d+H)?(\\d+M)?(\\d+S)?)?\$";
    
      print(regxPattern);
    
    RegExp re = new RegExp(regxPattern);
    
    if (re.hasMatch(durationString)) {
    
       for (var m in re.allMatches(durationString)) {
    
    
         print("total:"+m.group(0));
         print("Y:"+m.group(1));
         print("M:"+m.group(2));
         print("W:"+m.group(3));
         print("D:"+m.group(4));
         print("Time:"+m.group(5));
         print("H:"+m.group(6));
         print("M:"+m.group(7));
         print("S:"+m.group(8));
         Duration fastestMarathon = new Duration(hours:m.group(6), 
                                                 minutes:m.group(7), 
                                                 second,m.group(8));
    
       }
    
    }