Friday, 22 April 2016

Formatting time in Android/Java, the right way

I suppose this is very obvious for someone, but I spent a fair bit of time trying to understand what is the right, no, the right way to do time formatting in Java. I know about Joda, and don't really want to use it (because size, and frankly, I don't need all of it's features). I know about SimpleDateFormat and hate it because I have to hardcode my format. What I wanted is the way to use system-defined, user-preferred way to format time - i.e. if user specified 12-hour time, we want to add AM/PM, and if they happen to use Russian layout, that should magically become "ДП/ПП" however odd I would find this. This is, I think, the quickest the way to get it - using standard framework features:

When using this approach, you will get correctly formatted time, e.g. for 23:10 you will get "23:10" in 24-hour time, "11:10 PM" with English locale and 12-hour time, and "11:10 ПП" in Russian. Makes me very happy this is actually achievable without resorting to hacks like this, or, even worse, this.