JodaTime PeriodFormat, Elapsed time with only 1 Field

人盡茶涼 提交于 2019-12-05 08:14:31

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...

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