views:

9535

answers:

3

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

+4  A: 

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.

JamieH
This is the android.text.format.DateFormat rather than java.text.DateFormat.
jamesh
It's pretty typical of Android IME to have two classes that both claim to give you a result that is set to the default Locale but one doesn't. So yes, don't forget to use the android.text.format version of DateFormat (that doesn't even derive the java.util one LOL).
Max Howell
+1  A: 

This will do it:

Date date = new Date();
java.text.DateFormat dateFormat =
    android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
tronman
+1  A: 

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

So, i use fragment code as below for get current date in my format

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

or

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

In addition, you can use others format follow http://developer.android.com/reference/android/text/format/DateFormat.html

Fuangwith S.
Useful, but the question said "according to the device configuration". To me that implies using a format chosen based on the user's language/country, or chosen directly by the user, rather than hardcoding the choice of format.
Chris Boyle