So I have 2 date pickers for a start and end time, which give back a DateTime.
I need to calculate the duration between these two times in the format of "hours hr mins hr", so for example, "1 hr 30 mins". If there is a day difference, it will display "24 hr", so we use hours instead of days.
The problem I am having is that whatever way I got this working, it breaks if the user selects a month ahead. They never should choose a month ahead but are given the option to.
I get this error:
java.lang.UnsupportedOperationException: Unable to normalize as PeriodType is missing either years or months but period has a month/year amount: P1M3W6DT1H
at org.joda.time.Period.normalizedStandard(Period.java:1640)
And my code is:
Period durationHoursAndMinutes = new Period(startDate.toLocalDateTime(), endDate.toLocalDateTime()).normalizedStandard(PeriodType.time());
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendHours()
.appendSuffix(getResources().getString(R.string.mytrips_tripview_rail_waitTime_hr))
.appendSeparator(" ")
.appendMinutes()
.appendSuffix(getResources().getString(R.string.mytrips_tripview_rail_waitTime_min))
.toFormatter();
if(durationHoursAndMinutes.getMinutes() > 0){
return formatter.print(durationHoursAndMinutes);
}else {
return null;
}
I looked at the code for the PeriodType and it says to throw the exception if the months != 0, which it won't be. Just wondering if there is a way I can solve this. Thanks for any help
I suspect the simplest way to do this is just to pass the PeriodType
into the constructor instead:
new Period(
startDate.toLocalDateTime(),
endDate.toLocalDateTime(),
PeriodType.time());
Then you don't need to perform any other normalization.
See more on this question at Stackoverflow