Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JodaTime PeriodFormat, Elapsed time with only 1 Field

How can we display the elapsed time with only 1 field.

For example

  • Period = 1 Year 4 Months and 5 Days ==> Result = "1 Year ago"
  • Period = 3 Months 5 Days ==> Result = "3 Months ago"
  • Period = 4 Hours 5 Minutes ==> Result = "4 Hours ago"

So i just want the highest available field.

like image 997
firefly Avatar asked Apr 13 '12 11:04

firefly


2 Answers

There is no method in Joda-Time to do this, so you will have to test each field in turn manually.

like image 122
JodaStephen Avatar answered Oct 14 '22 00:10

JodaStephen


this will work

val startDate = new DateTime(millis).withZone(dateTimeZone)
val endDate = new DateTime(dateTimeZone)

val period = new Period(startDate, endDate)

val localized = PeriodFormat.wordBased(localeLanguageCode).print(period)
val splitted = localized.split(",|and")

So, the splitted value will be an Array containing the period segments, from a bigger period to the lower one.

The Head of the array is the value you are looking for.

slitted.head + "Ago."

*You should change the REGEX pattern on the split method depending on your Locale or if you are using a custom formatter rather than the default one (PeriodFormatterBuilder)

Ex. Array("4 years", "2 months", "5 days", "18 hours", "15 minutes", "10 seconds", "50 milliseconds")

like image 36
Juan Jose de la Torre Avatar answered Oct 14 '22 00:10

Juan Jose de la Torre