1

I am calculating time difference in hh:mm:ss.SSS format

DateTime dt1;
DateTime dt2;
Period period;
final DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss.SSS");

String endTime = "20:03:56.287";
String startTime = "19:59:27.322";
dt1 = format.parseDateTime(endTime);
dt2 = format.parseDateTime(startTime);
period = new Period(dt1,dt2);
System.out.println(period);

I get PT-4M-28.965S
How can I convert this to 00:04:28.965

jayantS
  • 817
  • 13
  • 29

3 Answers3

2

Period formatting is performed by the PeriodFormatter class:

PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroAlways()
                .appendHours().appendSeparator(":").appendMinutes()
                .appendSeparator(":").appendSeconds().appendSeparator(".")
                .appendMillis3Digit().toFormatter();
String dateString = formatter.print(period.normalizedStandard());

But this dateString will have a value as 0:-4:-28.-965, because you have defined your period as this:

String endTime = "20:03:56.287";
String startTime = "19:59:27.322";
dt1 = format.parseDateTime(endTime);
dt2 = format.parseDateTime(startTime);
period = new Period(dt1, dt2);

where the value of dt1 is greater than dt2, and so the - before mm:ss:SSS. To get the desired result, you need to change the order of parameters to period:

period = new Period(dt2, dt1);

and with this the above PeriodFormatter will return you 0:4:28.965.

Debojit Saikia
  • 10,532
  • 3
  • 35
  • 46
  • +1 for nice explanation. But I wanted the time in `hh:mm:ss.SSS` format. So, adding this `.minimumPrintedDigits(2)` method to the `formatter` object does the job. – jayantS Oct 11 '13 at 16:21
1

You will have to define a PeriodFormatterBuilder like so:

DateTime dt1;
DateTime dt2;
Period period;
final DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss.SSS");

String endTime = "20:03:56.287";
String startTime = "19:59:27.322";
dt1 = format.parseDateTime(endTime);
dt2 = format.parseDateTime(startTime);
period = new Period(dt1,dt2);

PeriodFormatter fmt = new PeriodFormatterBuilder()
  .appendHours()
  .appendSeparator(":")
  .appendMinutes()
  .appendSeparator(":")
  .appendSeconds()
  .appendSeparator(".")
  .appendMillis3Digit()
  .toFormatter();

System.out.println(fmt.print(period.normalizedStandard()));
Dirk Lachowski
  • 3,121
  • 4
  • 40
  • 66
0

Perhaps it's a value of Period.toString() Try using e.g. getHours() and other getXXX() methods to extract values.

Here is a better answer: Period to string

Community
  • 1
  • 1
Admit
  • 4,897
  • 4
  • 18
  • 26