376

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

Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

26 Answers26

315

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.

Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
JamieH
  • 4,788
  • 6
  • 28
  • 29
  • 43
    This is the android.text.format.DateFormat rather than java.text.DateFormat. – jamesh Sep 07 '09 at 23:31
  • 4
    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). – mxcl 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
  • 2
    @Harsha - to get around that issue, I chain my use of DateFormat so I only have to reference the Android class and therefore there aren't any ambiguous classes. final String dateStr = DateFormat.getDateFormat(this).format(d); You can use Android's format() method and have (IMHO) cleaner code and one less Object to instantiate. – Jerry Brady Aug 22 '11 at 19:06
  • 23
    This formatter only includes the date, not the time as the original question stated. Use DateUtils from the same package instead, see http://stackoverflow.com/questions/2983920/display-date-and-time-in-user-locale – Asmo Soinio Dec 02 '11 at 13:43
  • 23
    Please note this line: `DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());` The returned dateFormat is of type `java.text.DateFormat` (and NOT `android.text.format.DateFormat`) – Arye Rosenstein Feb 13 '11 at 06:53
  • Unfortunately this may not work on all devices. I'm testing with a HTC desire with "Select date format" in settings as ddd, MMM dd, yyyy and the dateformatter is returning MM/dd/yy! – RobCroll Dec 26 '12 at 18:25
  • For a full format, use an api. android.text.format.DateFormat.getLongDateFormat(Context); – allsoft May 30 '18 at 14:47
  • @JerryBrady your way is cleaner, you may want to consider writing it up as a separate answer. – ThomasW Nov 21 '18 at 08:10
233

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.

abmblob
  • 361
  • 2
  • 14
Fuangwith S.
  • 5,654
  • 8
  • 37
  • 41
  • 25
    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
  • 21
    also, don't forget that `hh:mm:ss` will give you `01:00:00` for 1 PM, you'll need to use `kk:mm:ss` to get `13:00:00` – dnet Apr 17 '12 at 11:51
  • 3
    @dnet `k` is hour in day (1-24), do you not mean `H`, which is hour in day (0-23), eg. HH:mm:ss? See: http://developer.android.com/reference/java/text/SimpleDateFormat.html – Joony Dec 07 '12 at 13:25
  • 2
    @Joony no, there's difference between `java.text.SimpleDateFormat` (what you linked and uses `H` for hours in the 0-23 range) and `android.text.format.DateFormat` (what the answer is about and uses `k` for hours in the 0-23 range) – dnet Dec 07 '12 at 22:51
  • @dnet After testing, you are correct about `k`, however, the documentation for `DateFormat` clearly states _For the canonical documentation of format strings, see SimpleDateFormat._ Very confusing. Or am I missing something? – Joony Dec 10 '12 at 11:24
  • Seems like format is a static method in android.text.format.DateFormat. – Muthukannan Kanniappan Dec 05 '13 at 14:15
  • @Joony I see your confusion and I had a huge WTF moment, see [this commit for `android...DateFormat`](https://github.com/android/platform_frameworks_base/commit/fc55c2ba49957bb696b98d290964dc36f4827190), but it seems `SimpleDateFormat` works as intended. – TWiStErRob Dec 20 '14 at 00:50
  • You can use also android.text.format.DateFormat.getLongDateFormat(). – Borzh Jun 17 '15 at 15:14
222

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


Dario Brux
  • 1,871
  • 1
  • 17
  • 15
Dany Pop
  • 3,590
  • 2
  • 21
  • 28
  • 8
    Thank you for putting all these cases in one place. If you could add cases for time only as well, this will make it a complete reference. – zeeshan Nov 21 '17 at 19:05
  • 1
    I am asking why the documentation is not so esaustive, Many thanks – Perry Oct 06 '20 at 04:05
  • For pattern approach use `DateFormat.getPatternInstance("dMMMMyyyyHHmm", Locale.ENGLISH).format(date)` -> `December 23, 2005, 17:37` – Nikolay Krasilnikov Aug 25 '23 at 11:29
43

Date to Locale date string:

Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);

Options:

   DateFormat.getDateInstance() 

- > Dec 31, 1969

   DateFormat.getDateTimeInstance() 

-> Dec 31, 1969 4:00:00 PM

   DateFormat.getTimeInstance() 

-> 4:00:00 PM

Ivo Stoyanov
  • 16,256
  • 8
  • 62
  • 65
24

Date and Time format explanation

EEE : Day ( Mon )
MMMM : Full month name ( December ) // MMMM February   
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2020 ) //both yyyy and YYYY are same
YYYY: Year ( 2020 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )
Shahzad Afridi
  • 2,058
  • 26
  • 24
Tippu Fisal Sheriff
  • 2,177
  • 11
  • 19
21

This will do it:

Date date = new Date();
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));
Maveňツ
  • 1
  • 12
  • 50
  • 89
tronman
  • 9,862
  • 10
  • 46
  • 61
17

Use SimpleDateFormat

Like this:

event.putExtra("starttime", "12/18/2012");

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(bundle.getString("starttime"));
neknek mouh
  • 1,802
  • 8
  • 27
  • 58
  • 5
    Yes, with **default locale** to avoid performance issues: `new SimpleDateFormat("my-format", Locale.getDefault());` – iutinvg Apr 10 '13 at 05:33
16

Here is the simplest way:

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);

    String time = df.format(new Date());

and If you are looking for patterns, check this https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Shubham Gupta
  • 1,123
  • 11
  • 16
14

Following this: http://developer.android.com/reference/android/text/format/Time.html

Is better to use Android native Time class:

Time now = new Time();
now.setToNow();

Then format:

Log.d("DEBUG", "Time "+now.format("%d.%m.%Y %H.%M.%S"));
FireZenk
  • 1,056
  • 1
  • 16
  • 28
  • 1
    @FireZenk: According to the [link]( http://developer.android.com/reference/android/text/format/Time.html) you provided: _This class has a number of issues and it is recommended that GregorianCalendar is used instead_. – ccpizza Jan 01 '15 at 14:30
  • 1
    Oh... this issue-info is newer than my comment, so that's a deprecated answer – FireZenk Jan 02 '15 at 14:59
10

Use these two as a class variables:

 public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
 private Calendar mDate = null;

And use it like this:

 mDate = Calendar.getInstance();
 mDate.set(year,months,day);                   
 dateFormat.format(mDate.getTime());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
9

This is my method, you can define and input and output format.

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
9

SimpleDateFormat

I use SimpleDateFormat without custom pattern to get actual date and time from the system in the device's preselected format:

public static String getFormattedDate() {
    //SimpleDateFormat called without pattern
    return new SimpleDateFormat().format(Calendar.getInstance().getTime());
}

returns:

  • 13.01.15 11:45
  • 1/13/15 10:45 AM
  • ...
Community
  • 1
  • 1
Tomas
  • 4,652
  • 6
  • 31
  • 37
8

Date format class work with cheat code to make date. Like

  1. M -> 7, MM -> 07, MMM -> Jul , MMMM -> July
  2. EEE -> Tue , EEEE -> Tuesday
  3. z -> EST , zzz -> EST , zzzz -> Eastern Standard Time

You can check more cheats here.

Sunil
  • 3,211
  • 3
  • 21
  • 21
7

Use build in Time class!

Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));
Igor Krumpak
  • 163
  • 2
  • 2
  • This is the optimal solution because it uses the lightweight Time object from the Android Framework: http://developer.android.com/reference/android/text/format/Time.html – Dean Wild Jan 29 '13 at 12:17
  • 13
    This is **not** the optimal solution: it doesn't respect the date format from the user's locale. – Dan Hulme Apr 25 '13 at 16:47
7

This code work for me!

Date d = new Date();
    CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
    Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();
Shahzad Afridi
  • 2,058
  • 26
  • 24
7

Shortest way:

// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())

%tR is short for %tH:%tM, < means to reuse last parameter(1$).

It is equivalent to String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM", Calendar.getInstance())

https://developer.android.com/reference/java/util/Formatter.html

k8C
  • 414
  • 4
  • 9
  • This is the shortest approach for sure, although it didn't work for me on Kotlin without removing the dollar symbol: `String.format("%1tY-% – Gnzlt Sep 14 '20 at 10:30
5

The other answers are generally correct. I should like to contribute the modern answer. The classes Date, DateFormat and SimpleDateFormat used in most of the other answers, are long outdated and have caused trouble for many programmers over many years. Today we have so much better in java.time, AKA JSR-310, the modern Java date & time API. Can you use this on Android yet? Most certainly! The modern classes have been backported to Android in the ThreeTenABP project. See this question: How to use ThreeTenABP in Android Project for all the details.

This snippet should get you started:

    int year = 2017, month = 9, day = 28, hour = 22, minute = 45;
    LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
    System.out.println(dateTime.format(formatter));

When I set my computer’s preferred language to US English or UK English, this prints:

Sep 28, 2017 10:45:00 PM

When instead I set it to Danish, I get:

28-09-2017 22:45:00

So it does follow the configuration. I am unsure exactly to what detail it follows your device’s date and time settings, though, and this may vary from phone to phone.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
4

I use it like this:

public class DateUtils {
    static DateUtils instance;
    private final DateFormat dateFormat;
    private final DateFormat timeFormat;

    private DateUtils() {
        dateFormat = android.text.format.DateFormat.getDateFormat(MainApplication.context);
        timeFormat = android.text.format.DateFormat.getTimeFormat(MainApplication.context);
    }

    public static DateUtils getInstance() {
        if (instance == null) {
            instance = new DateUtils();
        }
        return instance;
    }

    public synchronized static String formatDateTime(long timestamp) {
        long milliseconds = timestamp * 1000;
        Date dateTime = new Date(milliseconds);
        String date = getInstance().dateFormat.format(dateTime);
        String time = getInstance().timeFormat.format(dateTime);
        return date + " " + time;
    }
}
ViliusK
  • 11,345
  • 4
  • 67
  • 71
4

Locale

To get date or time in locale format from milliseconds I used this:

Date and time

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);

Date

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
dateFormat.format(date);

Time

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);

You can use other date style and time style. More info about styles here.

Wojtek
  • 1,210
  • 3
  • 18
  • 23
4

This code would return the current date and time:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chetan
  • 83
  • 1
  • 2
2

Try:

event.putExtra("startTime", "10/05/2012");

And when you are accessing passed variables:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Avoid j.u.Date

The Java.util.Date and .Calendar and SimpleDateFormat in Java (and Android) are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle gave up on them, supplanting them with the new java.time package in Java 8 (not in Android as of 2014). The new java.time was inspired by the Joda-Time library.

Joda-Time

Joda-Time does work in Android.

Search StackOverflow for "Joda" to find many examples and much discussion.

A tidbit of source code using Joda-Time 2.4.

Standard format.

String output = DateTime.now().toString(); 
// Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.

Localized format.

String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() ); 
// Full (long) format localized for this user's language and culture.
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

Back to 2016, When I want to customize the format (not according to the device configuration, as you ask...) I usually use the string resource file:

in strings.xml:

<string name="myDateFormat"><xliff:g id="myDateFormat">%1$td/%1$tm/%1$tY</xliff:g></string>

In Activity:

Log.d(TAG, "my custom date format: "+getString(R.string.myDateFormat, new Date()));

This is also useful with the release of the new Date Binding Library.

So I can have something like this in layout file:

<TextView
    android:id="@+id/text_release_date"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:padding="2dp"
    android:text="@{@string/myDateFormat(vm.releaseDate)}"
    tools:text="0000"
    />

And in java class:

    MovieDetailViewModel vm = new MovieDetailViewModel();
    vm.setReleaseDate(new Date());
alexpfx
  • 6,412
  • 12
  • 52
  • 88
0

The android Time class provides 3 formatting methods http://developer.android.com/reference/android/text/format/Time.html

This is how I did it:

/**
* This method will format the data from the android Time class (eg. myTime.setToNow())   into the format
* Date: dd.mm.yy Time: hh.mm.ss
*/
private String formatTime(String time)
{
    String fullTime= "";
    String[] sa = new String[2];

    if(time.length()>1)
    {
        Time t = new Time(Time.getCurrentTimezone());
        t.parse(time);
        // or t.setToNow();
        String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
        int x = 0;

        for(String s : formattedTime.split("\\s",2))
        {   
            System.out.println("Value = " + s);
            sa[x] = s;
            x++;
        }
        fullTime = "Date: " + sa[0] + " Time: " + sa[1];
    }
    else{
        fullTime = "No time data";
    }
    return fullTime;
}

I hope thats helpful :-)

Broo
  • 859
  • 4
  • 11
  • 21
0

It's too late but it may help to someone

DateFormat.format(format, timeInMillis);

here format is what format you need

ex: "HH:mm" returns 15:30

subrahmanyam boyapati
  • 2,836
  • 1
  • 18
  • 28
-3

Date - type

[Formatting and parsing date Times as strings][1]

EEE : Day ( Mon )
MMMM : Full month name ( December ) 
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2022 ) 
YYYY: Year ( 2022 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )
Ashish Kumar
  • 1,088
  • 8
  • 17