0

In my case i get the time in this format : PT2H3M20S i have no idea about the regex expression [using dart] so I just want to know how can we calculate milliseconds from above format.. thanks in advance

  Future<http.Response> getVideoDuration({var videoUri}) async {
    // print(videoUri);
    final BI_YT_API_KEY = "some_API";
    var lArr = videoUri.split('/');
    var lId = lArr[lArr.length - 1];
    var data = await http.get('https://www.googleapis.com/youtube/v3/videos' +
        "?id=$lId&part=contentDetails&key=$BI_YT_API_KEY");
    if (data.statusCode == 200) {
      var jom = json.decode(data.body);
      print(jom['items'][0]['contentDetails']['duration']);
      var duration = data.body[0];
    }
Why_So_Ezz
  • 160
  • 1
  • 7
  • The above format doesn't show milliseconds. Can you show your actual code as to where you are trying to receive milliseconds ? – Nisanth Reddy May 15 '21 at 08:04
  • @NisanthReddy yes it doesn't show milliseconds, I just want to separate the hour,minute, and seconds and calculate it to get milliseconds that's it ... but the problem is I don't know how to get that hour, minute, and seconds separately for every test case – Why_So_Ezz May 15 '21 at 08:08
  • Where are you getting this format from ? You need to post code for us to be able to help. – Nisanth Reddy May 15 '21 at 08:10
  • Regex doesn’t “do” anything to the input, except match it. It certainly doesn’t do any kind of transformation whatsoever. To convert this format to milliseconds you’re going to need to write some code. At a glance I would expect regex to be of little to no help. – Bohemian May 15 '21 at 08:19
  • @NisanthReddy i have added the code – Why_So_Ezz May 15 '21 at 08:22
  • What time is `PT2H3M20S` supposed to represent? Is it a timestamp or a duration? Is it supposed to mean 2 hours, 3 minutes, 20 seconds? If so, that's a duration, which should be stored a `Duration` object; a `DateTime` object would be inappropriate. – jamesdlin May 15 '21 at 08:37
  • @SourabhBankar. This is what you are looking for. https://stackoverflow.com/questions/22148885/converting-youtube-data-api-v3-video-duration-format-to-seconds-in-javascript-no. It is in Javascript. If you need it in Dart, ask. – Nisanth Reddy May 15 '21 at 08:46
  • @NisanthReddy yes perfect.. i need it in dart – Why_So_Ezz May 15 '21 at 08:57
  • Alright, will convert it and post. – Nisanth Reddy May 15 '21 at 08:58
  • @SourabhBankar. Fiiinally done. Check it out. – Nisanth Reddy May 15 '21 at 09:31

3 Answers3

4

Took some time. But fiinally done.

You can use it like this.

int seconds = convertTime("PT1H11S");

Here, seconds will be the converted duration in seconds. So, for PT1H11S, the answer will be, 3611 because of 1 hour == 3600 seconds + 11 seconds.

int convertTime(String duration) {

  RegExp regex = new RegExp(r'(\d+)');
  List<String> a = regex.allMatches(duration).map((e) => e.group(0)!).toList();

  if (duration.indexOf('M') >= 0 &&
      duration.indexOf('H') == -1 &&
      duration.indexOf('S') == -1) {
    a = ["0", a[0], "0"];
  }

  if (duration.indexOf('H') >= 0 && duration.indexOf('M') == -1) {
    a = [a[0], "0", a[1]];
  }
  if (duration.indexOf('H') >= 0 &&
      duration.indexOf('M') == -1 &&
      duration.indexOf('S') == -1) {
    a = [a[0], "0", "0"];
  }

  int seconds = 0;

  if (a.length == 3) {
    seconds = seconds + int.parse(a[0]) * 3600;
    seconds = seconds + int.parse(a[1]) * 60;
    seconds = seconds + int.parse(a[2]);
  }

  if (a.length == 2) {
    seconds = seconds + int.parse(a[0]) * 60;
    seconds = seconds + int.parse(a[1]);
  }

  if (a.length == 1) {
    seconds = seconds + int.parse(a[0]);
  }
  return seconds;
}
Nisanth Reddy
  • 5,967
  • 1
  • 11
  • 29
1

Note: I do not know flutter but I have heard that a flutter developer should be able to use Java code. This answer is based on Java.

tl;dr

With Java, all you need is:

Duration.parse("PT2H3M20S").toMillis()

java.time.Duration is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.

If you have gone through the above links, you might have already noticed that PT2H3M20S specifies a duration of 2 hours 3 minutes 20 seconds that you can parse to a Duration object which you can convert into milliseconds.

Demo:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        String strIso8601Duration = "PT2H3M20S";
        Duration duration = Duration.parse(strIso8601Duration);
        long millis = duration.toMillis();
        System.out.println(millis);
    }
}

Output:

7400000

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


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

I also managed to get the duration in seconds using dart (If in case someone needed it)

/// For duration  = 2H1M48S
converToSeconds(String duration){

      var hour = "", minute = "", seconds = "";
      var tempList = duration.split('');

      /// HOUR
      if (tempList.contains('H')) {
        var ind = tempList.indexOf('H');
        for (int i = 0; i < ind; i++) {
          hour = hour + tempList[i];
        }
        tempList.removeRange(0, ind + 1);
      }

      /// MINUTES
      if (tempList.contains('M')) {
        var ind = tempList.indexOf('M');
        for (int i = 0; i < ind; i++) {
          minute = minute + tempList[i];
        }
        tempList.removeRange(0, ind + 1);
      }

      /// SECONDS
      if (tempList.contains('S')) {
        var ind = tempList.indexOf('S');
        for (int i = 0; i < ind; i++) {
          seconds = seconds + tempList[i];
        }
        tempList.removeRange(0, ind + 1);
      }

      /// CONVER TO INT
      hour = hour != "" ? hour : '0';
      seconds = seconds != "" ? seconds : '0';
      minute = minute != "" ? minute : '0';

      var ms = ((int.parse(hour) * 3600 + int.parse(minute) * 60) + int.parse(seconds));
}
Why_So_Ezz
  • 160
  • 1
  • 7