JodaTime PeriodFormat, Elapsed time with only 1 Field

ε祈祈猫儿з 提交于 2019-12-22 05:26:11

问题


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.


回答1:


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




回答2:


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")




回答3:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!