homeAndroid Stuff

Relative Timespans

This is going to be a short post because I’ve seen a lot of custom implementations to provide the well known a few minutes ago labels, which are often hard to maintain and rarely properly localized.

There already is an implementation for this—no, it’s not JodaTime.

Enter DateUtils

For those of you eager to just read the documentation, you can find it here. It provides an interface to display localized dates and timespans. There are many options to show or hide the year, display the weekday, or include the month by its name or number.

DateUtils.getRelativeTimeSpanString(then, now, minResolution, flags);

Below is a screenshot from a simple app where you can check and uncheck the options with a simple preview. Check out the full source code here. The first line is getRelativeDateTimeString() and the second line shows getRelativeTimeSpanString(). You can also try the app yourself here.


The only downside is, that you have no further control about the format of the returned string. Whether am / pm is displayed depends on the locale and user settings, which on the one hand is perfectly reasonable, on the other hand might lead to some discussions with your designer.

Another thing worth mentioning is that some strings can and will appear differently on various devices. While one might say Yesterday another device could display One day ago. But I don’t think that the developer should have to care about this—if every developer used DateUtils the user would still get a consistent experience within all of his apps.