DateUtils.getRelativeTimeSpanString() and Timezones

If you're thinking about DateUtils.getRelativeTimeSpanString(): don't.

After a long struggle I've finally given up on the method. It seems so tempting - an easy way of showing the user how far away an event will be (or was). But without being able to pass a timezone you run into an intractable situation which makes it unusable.

The critical problem relates to how it calculates a number of days. It relies on Time.getJulianDay(), which would work - except you have no control over the timezone parameter. Instead, it uses the default device timezone. This can cause day calculations to be incorrect as you might shift a Julian day when applying the device timezone to the milliseconds provided from another timezone.

Before 4.3, the situation was even worse: the internal Time used in DateUtils (for calls to getJulianDay()) is cached. That meant if your app usesgetRelativeTimeSpanString(), then the device's timezone changes, you're now calculating the # of days based on the previous device timezone!

The only comprehensive solution I can come up with is to implement my own version of getRelativeTimeSpanString() that adds the timezone element. You just need to account for timezones when you're dealing with any period of time greater than hours.

comments powered by Disqus