Tip – Working with Human Readable Date and Time in Android

In the course of developing my first 3 apps for Android, I had read over (skimmed of course) the documentation page for SimpleDateFormat probably a half a dozen times before I came across the following gem which is the first thing you need to know because you are more than likely displaying your date to a human:

If you’re formatting for human use, you should use an instance returned from DateFormat as described above. This code:

DateFormat[] formats = new DateFormat[] {

DateFormat.getDateInstance(),

DateFormat.getDateTimeInstance(),

DateFormat.getTimeInstance(),

};

for (DateFormat df : formats) {

System.out.println(df.format(new Date(0)));

}

Produces this output when run on an en_US device in the America/Los_Angeles time zone:

Dec 31, 1969

Dec 31, 1969 4:00:00 PM

4:00:00 PM

So the takeaway message for lazy readers like myself: use “DateFormat.getDateInstance()”, “DateFormat.getDateTimeInstance()” and “DateFormat.getTimeInstance()” to return dates formatted in one of the three respective standards.

Leave a comment