Date & Time

From the Google material design documentation

How you format the date and time depends on a few factors:

  • If the time or date is the current one
  • Whether you are using the 12-hour or 24-hour clock
  • How specific you need to be

I. Declare a TextView in your layout file.

<TextView  
    android:id="@+id/hora"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

II. In your Activity, get the time format which corresponds the locale and configuration of the device.

DateFormat timeFormat = DateFormat.getTimeFormat(context);  

Note: getTimeFormat() is a method of the DateFormat in the android.text.format package, be careful, don't use the class DateFormat inside the java.text package.

III. Get the text with the current time and insert it in the TextView

TextView hourTextView = (TextView) findViewById(R.id.hourTextView);  
horaTextView.setText(timeFormat.format(new Date()));  

 Date

I. Declare a TextView in your layout file.

<TextView  
    android:id="@+id/fecha"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

II. In your Activity, get the format of the date which corresponds to the locale and configuration of the devices. Depending on the available space you can use medium, long or numeric format.

DateFormat numericDateFormat =  
    DateFormat.getDateFormat(context);

DateFormat mediumDateFormat =  
    DateFormat.getMediumDateFormat(context);

DateFormat longDateFormat =  
    DateFormat.getLongDateFormat(context);

III. Get the text with the actual date and put it in your TextView

TextView fechaTextView = (TextView) findViewById(R.id.dateTextView);  
fechaTextView.setText(longDateFormat.format(new Date()));  

Nota: The DateFormat class allows many configurations according to your specific needs, for more information see the development guides.

Article originally written by Rafa Vázquez at materialdoc.es