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.
There is no method in Joda-Time to do this, so you will have to test each field in turn manually.
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")
The obvious algorithm would be to test if year > 0, in which case you use it, if not test if month > 0 etc. There might be something more elegant but that would work in less than 15 lines of code...
来源:https://stackoverflow.com/questions/10140141/jodatime-periodformat-elapsed-time-with-only-1-field