How to format date and time in Android?

AndroidDateTimeFormattingFormat

Android Problem Overview


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

Android Solutions


Solution 1 - 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.

Solution 2 - Android

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.

Solution 3 - Android

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


Solution 4 - Android

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

Solution 5 - Android

This will do it:

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

Solution 6 - Android

Use SimpleDateFormat

Like this:

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

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(bundle.getString("starttime"));

Solution 7 - Android

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

Solution 8 - Android

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"));

Solution 9 - Android

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 )

Solution 10 - Android

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());

Solution 11 - Android

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;

}

Solution 12 - Android

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
  • ...

Solution 13 - Android

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"));

Solution 14 - Android

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

Solution 15 - Android

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.

Solution 16 - Android

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();

Solution 17 - Android

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.

Solution 18 - Android

This code would return the current date and time:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}

Solution 19 - Android

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.

Solution 20 - Android

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;
    }
}

Solution 21 - Android

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"));

Solution 22 - Android

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.

Solution 23 - Android

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());

Solution 24 - Android

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 :-)

Solution 25 - Android

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

Solution 26 - Android

Date from type

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 )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpupenoView Question on Stackoverflow
Solution 1 - AndroidJamieHView Answer on Stackoverflow
Solution 2 - AndroidFuangwith S.View Answer on Stackoverflow
Solution 3 - AndroidDany PopView Answer on Stackoverflow
Solution 4 - AndroidIvo StoyanovView Answer on Stackoverflow
Solution 5 - AndroidtronmanView Answer on Stackoverflow
Solution 6 - Androidneknek mouhView Answer on Stackoverflow
Solution 7 - AndroidShubham GuptaView Answer on Stackoverflow
Solution 8 - AndroidFireZenkView Answer on Stackoverflow
Solution 9 - AndroidTippu Fisal SheriffView Answer on Stackoverflow
Solution 10 - Androiduser1367623View Answer on Stackoverflow
Solution 11 - AndroidJorgesysView Answer on Stackoverflow
Solution 12 - AndroidTomasView Answer on Stackoverflow
Solution 13 - AndroidIgor KrumpakView Answer on Stackoverflow
Solution 14 - Androidk8CView Answer on Stackoverflow
Solution 15 - AndroidSunilView Answer on Stackoverflow
Solution 16 - AndroidShahzad AfridiView Answer on Stackoverflow
Solution 17 - AndroidOle V.V.View Answer on Stackoverflow
Solution 18 - AndroidchetanView Answer on Stackoverflow
Solution 19 - AndroidWojtekView Answer on Stackoverflow
Solution 20 - AndroidViliusKView Answer on Stackoverflow
Solution 21 - AndroidAbhishek Singh RathaurView Answer on Stackoverflow
Solution 22 - AndroidBasil BourqueView Answer on Stackoverflow
Solution 23 - AndroidalexpfxView Answer on Stackoverflow
Solution 24 - AndroidBrooView Answer on Stackoverflow
Solution 25 - Androidsubrahmanyam boyapatiView Answer on Stackoverflow
Solution 26 - AndroidAshish KumarView Answer on Stackoverflow