0

I am trying to calculate the time between two dates and show the difference in time in the UI as x mins ago, x days ago, x weeks ago etc (depending on the length of time).

The first date is a published date which is given to me by the api. I then format this date to yyyy-MM-dd HH:mm:ss. Second date is the current time.

val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
val time = sdf.parse("$year-$month-$day $hours").time   // 2019-03-14 13:00:55
val now = System.currentTimeMillis()
val relative = DateUtils.getRelativeTimeSpanString(time, now, 0L, DateUtils.FORMAT_ABBREV_ALL)

However, when I print relative, I get Mar 14 when I would expect x months ago.

Can't tell what I'm missing apart from I have read somewhere that getRelativeTimeSpanString() only works for 7 days, but the documentation doesn't state this so not sure if that's the case?

Any help to solve this would be appreciated!

Jason
  • 209
  • 2
  • 13

1 Answers1

0

It's a feature.

You have minimum resolution of 0 milliseconds and hence the time is printed exactly. It doesn't make sense to have output like "16 weeks ago 13:00:55".

You could change the minimum resolution to DateUtils.WEEK_IN_MILLIS to get output like "16 weeks ago".

There's also another DateUtils method that allows you to specify the transition resolution:

the elapsed time (in milliseconds) at which to stop reporting relative measurements. Elapsed times greater than this resolution will default to normal date formatting. For example, will transition from "7 days ago" to "Dec 12" when using WEEK_IN_MILLIS

In theory that would work, but in practice it is capped at WEEK_IN_MILLIS.

Under the hood, it's RelativeDateTimeFormatter doing the work and you can learn more by inspecting its source.

If you really need "months ago" resolution, forget about DateUtils and roll your own implementation. For example with java.time / ThreeTenBP APIs: https://stackoverflow.com/a/56450659/101361

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Ok, thanks. That makes sense. I'll look for another solution/check out the one you mentioned. – Jason Jul 08 '19 at 15:04