How do you format date and time in Android?


How do you format correctly according to the device configuration a date and time when having year, month, day, hour and minute?

1/17/2009 11:41:37 PM

Accepted Answer

Use the standard Java DateFormat class.

For example to display the current date and time do the following:

Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

You can initialise a Date object with your own values, however you should be aware that the constructors have been deprecated and you should really be using a Java Calendar object.

10/1/2010 9:12:51 AM

In my opinion, android.text.format.DateFormat.getDateFormat(context) makes me confused because this method returns java.text.DateFormat rather than android.text.format.DateFormat - -".

So, I use the fragment code as below to get the current date/time in my format.

android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());


android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

In addition, you can use others formats. Follow DateFormat.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow