How to format date and time in Android?
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.
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());
or
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.
You can use DateFormat
. Result depends on default Locale of the phone, but you can specify Locale too :
https://developer.android.com/reference/java/text/DateFormat.html
This is results on a
DateFormat.getDateInstance().format(date)
FR Locale : 3 nov. 2017
US/En Locale : Jan 12, 1952
DateFormat.getDateInstance(DateFormat.SHORT).format(date)
FR Locale : 03/11/2017
US/En Locale : 12.13.52
DateFormat.getDateInstance(DateFormat.MEDIUM).format(date)
FR Locale : 3 nov. 2017
US/En Locale : Jan 12, 1952
DateFormat.getDateInstance(DateFormat.LONG).format(date)
FR Locale : 3 novembre 2017
US/En Locale : January 12, 1952
DateFormat.getDateInstance(DateFormat.FULL).format(date)
FR Locale : vendredi 3 novembre 2017
US/En Locale : Tuesday, April 12, 1952
DateFormat.getDateTimeInstance().format(date)
FR Locale : 3 nov. 2017 16:04:58
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date)
FR Locale : 03/11/2017 16:04
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date)
FR Locale : 03/11/2017 16:04:58
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(date)
FR Locale : 03/11/2017 16:04:58 GMT+01:00
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL).format(date)
FR Locale : 03/11/2017 16:04:58 heure normale d’Europe centrale
DateFormat.getTimeInstance().format(date)
FR Locale : 16:04:58
DateFormat.getTimeInstance(DateFormat.SHORT).format(date)
FR Locale : 16:04
DateFormat.getTimeInstance(DateFormat.MEDIUM).format(date)
FR Locale : 16:04:58
DateFormat.getTimeInstance(DateFormat.LONG).format(date)
FR Locale : 16:04:58 GMT+01:00
DateFormat.getTimeInstance(DateFormat.FULL).format(date)
FR Locale : 16:04:58 heure normale d’Europe centrale