Android Tricks #1: Formatting dates and time on Android

Users expect apps to be localized and that involves dealing with date and time formatting. Here’s how to do it easily and efficiently.

Let’s face it: Many of us are spoiled by our smartphones and we expect a lot from the apps we use every day. One of these things is localization.

Localization on Android is quite easy. You deal with strings.xml files, Android Studio has a decent translations editor and Android itself has a bunch of default strings, such as “OK” and “Cancel”, that you can use in dialogs, etc.

So, what’s the problem? Well, translations are one thing. Formatting dates and time is another thing entirely, and it can be an rather overwhelming if you don’t know where to look.

Android has a variety of “hidden gems” in the shape of utility classes and DateUtils is one of those useful gems.

With DateUtils you can format dates and time, as well as handle elapsed time, time and date ranges, day and month names, etc. Best of all? Everything is localized and formatted specifically for the user’s locale.

Let’s take a look at what the class can do. All examples shown below use the US date and time format conventions.

Date and time formatting

Let’s start with something that most people will use in their apps: Simple date and time formatting.

The formatDateTime() method is quite powerful and can do a lot to help you format both dates and time perfectly, regardless of the user’s locale.

Here are some examples:

The documentation offers quite a few other examples of which kind of output you can achieve, although you’ll have to experiment with the flag combination yourself.

Date range formatting

The formatDateRange() method helps you format a date range. Once again you can use flags to change how the data is presented.

… and there’s more

That’s just some of the cool stuff you can do with the DateUtils class. There’s a bunch of other methods in there that you can play with.

Here’s some of the more interesting ones for you to experiment with:

There are of course a number of cases where it makes more sense to use a Calendar instance or the SimpleDateFormat class, but there’s a lot of good stuff in DateUtils and it’s a shame not to use it.

Show your support

Clapping shows how much you appreciated Michell Bak’s story.