2

I want to make an analysis of some time barriers and I'm having some doubts about the best approach to define 'Period'.

I'm working with time passed from the start, I mean:

Start - "00:00:00"
Checkpoint 1 - "2:10:02"
End - "03:00:00"

So, what kind of object should I use to translate the string? Later I'll want to make some averages, etc.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
ruigomes
  • 21
  • 1
  • 1
    is you code java8-able? – ΦXocę 웃 Пepeúpa ツ Jan 21 '19 at 14:44
  • 1
    [Period::between](https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#between-java.time.LocalDate-java.time.LocalDate-) – achAmháin Jan 21 '19 at 14:44
  • 1
    Perhaps you're looking for [`Duration.parse()`](https://docs.oracle.com/javase/10/docs/api/java/time/Duration.html#parse(java.lang.CharSequence)) (requires Java 8 or later). – John Bollinger Jan 21 '19 at 14:48
  • [`Duration`](https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html). It prints differently, but search for questions about parsing and formatting the format with colons that you use, they are out there. – Ole V.V. Jan 22 '19 at 10:15
  • I take it that the times are relative to the start time? Not times of day, are they? – Ole V.V. Jan 22 '19 at 10:16

2 Answers2

0

If you can use LocalTime for example, you could use this and manipulate it however necessary:

String start = "02:10:02";
String end = "03:00:00";

LocalTime lt = LocalTime.parse(start);
LocalTime lt2 = LocalTime.parse(end);
Duration dur = Duration.between(lt, lt2);
System.out.println("Diff is: " + dur.getSeconds());

Output:

Diff is: 2998

Then do whatever you need with the seconds.

achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • If the times are not time of day, `LocalTime` is incorrect. `Duration` is good under all circumstances. – Ole V.V. Jan 22 '19 at 10:18
0

You could use LocalTime and Duration although you will need a custom format to parse time with single hour digit.

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("H:mm:ss");

LocalTime start = LocalTime.parse("00:00:00", fmt);
LocalTime checkpoint = LocalTime.parse("2:10:02", fmt);
LocalTime end = LocalTime.parse("03:00:00", fmt);

System.out.println(Duration.between(start, checkpoint)); // PT2H10M2S
System.out.println(Duration.between(checkpoint, end)); // PT49M58S
System.out.println(Duration.between(start, end)); // PT3H
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111