Snippet: DateUtils

This is the first in a new series of posts I’m going to regularly publish (weekly-ish) of code snippets which could save you a lot of #AndroidDev time. The first of which is about one of my favourite classes in Android: DateUtils.

It’s Javadoc keeps things nice and short:

This class contains various date-related utilities for creating text for things like elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc.

It contains a lot of static methods to help you format date, times, time deltas into a human-readable String. The best bit though is that it handles all of the localisation for you!

Example Use

So I’ll give you an example of where you might use this class. Say you have a Twitter timeline and want to display how long ago a tweet was sent. You could write the code yourself, but you’d quickly end up with a long method which is difficult to test. So instead, use DateUtils.getRelativeTimeSpanString(...). At the time of writing there five versions of the method, but the one I tend to use is:

CharSequence getRelativeTimeSpanString (long time, long now, long minResolution)

So how do you use the method? Well it’s pretty simple:

  • time – The time of the Tweet (epoch format).
  • now – System.currentTimeMillis()
  • minResolution – This depends how accurate you granular you want the String to be. I tend to use SECOND_IN_MILLIS so the smallest unit of time will be seconds.

Which returns something like this (in English):

2 seconds ago

Or this in German:

Vor 33 Sekunden

Bottom Line

If you’re doing any kind of date or time formatting, make sure you check to see if it is already implemented in DateUtils. It will save you a lot of time!