1

I'm having the following data:

"startAt": "PT0S",
"endAt": "PT21M12.667S"

startAt defines the start of a video and endAt the end of the video. How can I calculate the time between these points? I guess its ISO 8601 and I am using Java, but the library I tried (Joda) doens't work with the endAt paramter.

Diego C Nascimento
  • 2,801
  • 1
  • 17
  • 23
Dominik
  • 1,016
  • 11
  • 30

2 Answers2

4

These are ISO-8601 period values (not points in time) - and Joda Time handles them fine:

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        String startText = "PT0S";
        String endText = "PT21M12.667S";

        PeriodFormatter format = ISOPeriodFormat.standard();
        Period start = format.parsePeriod(startText);
        Period end = format.parsePeriod(endText);

        Duration duration = end.minus(start).toStandardDuration();
        System.out.println(duration); // PT1272.667S
        System.out.println(duration.getMillis()); // 1272667
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Do you know everything? Or are you just a research god? – Cruncher Sep 17 '13 at 13:08
  • @Cruncher: Well date and time APIs are very close to my heart, so it didn't take long to whip up the sample code... – Jon Skeet Sep 17 '13 at 13:17
  • Thank you very much Sir! I just didn't understand the point char between the 12 and the 667 but this works fine! Keep up the great work :) – Dominik Sep 17 '13 at 17:07
0

Using Java-8 standard library

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

Demo:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        String startAt = "PT0S";
        String endAt = "PT21M12.667S";
        Duration start = Duration.parse(startAt);
        Duration end = Duration.parse(endAt);
        long millis = end.minus(start).toMillis();
        System.out.println(millis);
    }
}

Output:

1272667

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

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