Thursday, June 2, 2011

Date and time

URL:http://stackoverflow.com/questions/454315/how-do-you-format-date-and-time-in-android







5 Answers

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.




6  
This is the android.text.format.DateFormat rather than java.text.DateFormat. – jamesh Sep 7 '09 at 23:31

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 Jul 20 '10 at 14:14

am having problem with what i should import - i mean lib files :( – Harsha M V Dec 27 '10 at 12:30
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





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 Oct 14 '10 at 16:26
This will do it:
Date date = new Date();
java.text.DateFormat dateFormat =
    android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
link|edit|flag


am having problem with what i should import - i mean lib files :( – Harsha M V Dec 27 '10 at 12:30

If you use Eclipse, press CTRL-SHIFT-O (letter "o") :) – Select0r Dec 28 '10 at 17:26

Although accepted, the answer wasn't really correct, because getDateFormat(getApplicationContext()) method returns date format only, not
a date and time when having year, month, day, hour and minute
You can find correct answer here.





Please note that in the answer above selected by the owner as the best answer, in the line:
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
the returned dateFormat is of type java.text.DateFormat (and NOT android.text.format.DateFormat)

No comments:

Post a Comment