A blog for technology, SEO tips, website development and open source programming.

Display current date on your Android app

3 16,856

android_alarmThis post simply shows how you can get current date and time inside Android layout and insert it in a TextView. Also it covers how you can format the date. 

The official reference guide  can be found here

Option 1

This example takes the default date without any formatting and outputs:  2013-11-15 09:46:33

Date = (TextView) findViewById(R.id.txtDate);
String Date= DateFormat.getDateTimeInstance().format(new Date());
textView.setText(Date);

Option 2

This example shows how you can take individually year , month or year.
The result is: 15 – 11 – 2013
Date = (TextView) findViewById(R.id.txtDate);
final Calendar cal = Calendar.getInstance();
dd = cal.get(Calendar.DAY_OF_MONTH);
mm = cal.get(Calendar.MONTH);
yy = cal.get(Calendar.YEAR);
// set current date into textview
Date.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(yy).append(" ").append("-").append(mm + 1).append("-")
.append(dd));

Option 3

This example shows how you can format the date.
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.UK);
System.err.format("%30s %sn", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %sn", format, sdf.format(new Date(0)));
}

This outputs:
yyyy-MM-dd 2013-11-15
yyyy-MM-dd 2013-11-15
yyyy-MM-dd HH:mm 2013-11-15 09:46
yyyy-MM-dd HH:mm 2013-11-15 09:46
yyyy-MM-dd HH:mmZ 2013-11-15 09:46-0200
yyyy-MM-dd HH:mmZ 2013-11-15 09:46+0000
yyyy-MM-dd HH:mm:ss.SSSZ 2013-11-15 16:00:00.000-0800
yyyy-MM-dd HH:mm:ss.SSSZ 2013-11-15 00:00:00.000+0000
yyyy-MM-dd’T’HH:mm:ss.SSSZ 2013-11-15 T16:00:00.000-0800
yyyy-MM-dd’T’HH:mm:ss.SSSZ 2013-11-15 T00:00:00.000+0000

To get day name month day number and year you need to do this “EEEE, MMMM dd, yyyy” -> “Friday, November 15, 2013”

Also Read – How to Display version number on your Android app

 

3 Comments
  1. Don says

    Where do I enter all this stuff?

    1. Admin says

      You have to add the code inside an Android Activity, for your reference check http://developer.android.com/reference/android/app/Activity.html

  2. surani saunak says

    Fabulous tips thanks..
    if you want to know more about android-basic-tutorial-get-current-date then goto this link.

    http://exandroidstudio.blogspot.in/2015/02/android-basic-tutorial-get-current-date.html

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More