Display the current time and date in an Android application

AndroidDatetimeAndroid Date

Android Problem Overview


How do I display the current date and time in an Android application?

Android Solutions


Solution 1 - Android

Okay, not that hard as there are several methods to do this. I assume you want to put the current date & time into a TextView.

String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);

There is more to read in the documentation that can easily be found here . There you'll find more information on how to change the format used for conversion.

Solution 2 - Android

public class XYZ extends Activity {
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.main);
		
		Calendar c = Calendar.getInstance();
		System.out.println("Current time => "+c.getTime());
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		// formattedDate have current date/time
		Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
		
		
	  // Now we display formattedDate value in TextView
		TextView txtView = new TextView(this);
		txtView.setText("Current Date and Time : "+formattedDate);
		txtView.setGravity(Gravity.CENTER);
		txtView.setTextSize(20);
		setContentView(txtView);
	}
	
}

enter image description here

Solution 3 - Android

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    Thread myThread = null;

    Runnable runnable = new CountDownRunner();
    myThread= new Thread(runnable);   
    myThread.start();

}

public void doWork() {
    runOnUiThread(new Runnable() {
        public void run() {
            try{
                TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
                    Date dt = new Date();
                    int hours = dt.getHours();
                    int minutes = dt.getMinutes();
                    int seconds = dt.getSeconds();
                    String curTime = hours + ":" + minutes + ":" + seconds;
                    txtCurrentTime.setText(curTime);
            }catch (Exception e) {}
        }
    });
}


class CountDownRunner implements Runnable{
    // @Override
    public void run() {
            while(!Thread.currentThread().isInterrupted()){
                try {
                doWork();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                }catch(Exception e){
                }
            }
    }
}

Solution 4 - Android

The obvious choices for displaying the time are the AnalogClock View and the DigitalClock View.

For example, the following layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
  	android:layout_width="fill_parent"
  	android:layout_height="fill_parent" 
  	android:orientation="vertical">

    <AnalogClock
    	android:layout_width="fill_parent" 
    	android:layout_height="wrap_content"/>
    	
    <DigitalClock 
    	android:layout_width="fill_parent" 
    	android:layout_height="wrap_content" 
    	android:gravity="center" 
    	android:textSize="20sp"/>
</LinearLayout>

Looks like this:

screenshot

Solution 5 - Android

In case you want a single line of code:

String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

The result is "2016-09-25 16:50:34"

Solution 6 - Android

My own working solution:

Calendar c = Calendar.getInstance();

String sDate = c.get(Calendar.YEAR) + "-" 
+ c.get(Calendar.MONTH)
+ "-" + c.get(Calendar.DAY_OF_MONTH) 
+ " at " + c.get(Calendar.HOUR_OF_DAY) 
+ ":" + c.get(Calendar.MINUTE);

Hope this helps!

Solution 7 - Android

If you want to get the date and time in a specific pattern you can use

Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());

Solution 8 - Android

From https://stackoverflow.com/questions/7054945/how-to-get-full-date-with-correct-format:

Please, use

android.text.format.DateFormat.getDateFormat(Context context)
android.text.format.DateFormat.getTimeFormat(Context context)

to get valid time and date formats in sense of current user settings (12/24 time format, for example).

import android.text.format.DateFormat;

private void some() {
    final Calendar t = Calendar.getInstance();
    textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}

Solution 9 - Android

Here is the code which worked for me. Please try this. It is a simple method which takes time and date from a system call.

public static String getDatetime() {
    Calendar c = Calendar .getInstance();
    System.out.println("Current time => "+c.getTime());
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mms");
    String formattedDate = df.format(c.getTime());
    return formattedDate;
}

Solution 10 - Android

Use:

Calendar c = Calendar.getInstance();

int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hour = c.get(Calendar.HOUR);
String time = hour + ":" + minutes + ":" + seconds;


int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + month + "/" + year;

// Assuming that you need date and time in a separate
// textview named txt_date and txt_time.

txt_date.setText(date);
txt_time.setText(time);

Solution 11 - Android

String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

Use formattedDate as your String filled with the date.
In my case: mDateButton.setText(formattedDate);

Solution 12 - Android

Actually, you're best off with the TextClock widget. It handles all of the complexity for you and will respect the user's 12/24hr preferences. http://developer.android.com/reference/android/widget/TextClock.html

Solution 13 - Android

To display the current date function:

Calendar c = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(c.getTime());
Date.setText(date);

You must want to import

> import java.text.SimpleDateFormat; > import java.util.Calendar;

You must want to use

TextView Date;
Date = (TextView) findViewById(R.id.Date);

Solution 14 - Android

Calendar c = Calendar.getInstance();
int month=c.get(Calendar.MONTH)+1;
String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
"T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);

This will give date time format like 2010-05-24T18:13:00

Solution 15 - Android

This would give the current date and time:

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

Solution 16 - Android

Simply copy this code and hope this works fine for you.

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());

Solution 17 - Android

Try the below code:

SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "yyyy/MM/dd HH:mm:ss");

Calendar cal = Calendar.getInstance();
System.out.println("time => " + dateFormat.format(cal.getTime()));

String time_str = dateFormat.format(cal.getTime());

String[] s = time_str.split(" ");

for (int i = 0; i < s.length; i++) {
     System.out.println("date  => " + s[i]);
}

int year_sys = Integer.parseInt(s[0].split("/")[0]);
int month_sys = Integer.parseInt(s[0].split("/")[1]);
int day_sys = Integer.parseInt(s[0].split("/")[2]);

int hour_sys = Integer.parseInt(s[1].split(":")[0]);
int min_sys = Integer.parseInt(s[1].split(":")[1]);

System.out.println("year_sys  => " + year_sys);
System.out.println("month_sys  => " + month_sys);
System.out.println("day_sys  => " + day_sys);

System.out.println("hour_sys  => " + hour_sys);
System.out.println("min_sys  => " + min_sys);

Solution 18 - Android

String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();

Solution 19 - Android

You Can try this way

Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());

Solution 20 - Android

If you wish to work with date/time in android I recommend you to use ThreeTenABP which is a version of java.time.* package (available starting from API 26 on android) shipped with Java 8 available as a replacement for java.util.Date and java.util.Calendar.

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);

Solution 21 - Android

For Show Current Date and Time on Textview

    /// For Show Date
    String currentDateString = DateFormat.getDateInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewdate.setText(currentDateString);
    /// For Show Time
    String currentTimeString = DateFormat.getTimeInstance().format(new Date());
    // textView is the TextView view that should display it
    textViewtime.setText(currentTimeString);

Check full Code Android – Display the current date and time in an Android Studio Example with source code

Solution 22 - Android

To get current Time/Date just use following code snippet:

To use Time:

SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
String strTime = simpleDateFormatTime.format(now.getTime());

To use Date:

SimpleDateFormat simpleDateFormatDate = new SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault());    
String strDate = simpleDateFormatDate.format(now.getTime());

and you are good to go.

Solution 23 - Android

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59
String AMPM;
if (c.get(Calendar.AM_PM) == 0) {
    AMPM = "AM";
} else {
    AMPM = "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
QuestionBIBEKRBARALView Question on Stackoverflow
Solution 1 - AndroidZordidView Answer on Stackoverflow
Solution 2 - Androiduser647826View Answer on Stackoverflow
Solution 3 - AndroidPrashantView Answer on Stackoverflow
Solution 4 - AndroidDave WebbView Answer on Stackoverflow
Solution 5 - AndroidMahdi AstaneiView Answer on Stackoverflow
Solution 6 - AndroidfredView Answer on Stackoverflow
Solution 7 - AndroidNam VuView Answer on Stackoverflow
Solution 8 - Androidwonder.miceView Answer on Stackoverflow
Solution 9 - AndroidvinothView Answer on Stackoverflow
Solution 10 - AndroidJoy PanchalView Answer on Stackoverflow
Solution 11 - AndroidBartView Answer on Stackoverflow
Solution 12 - AndroidGabeView Answer on Stackoverflow
Solution 13 - AndroidHabeeb Rahman kalathilView Answer on Stackoverflow
Solution 14 - AndroidThomas V JView Answer on Stackoverflow
Solution 15 - AndroidchetanView Answer on Stackoverflow
Solution 16 - AndroidParth BhayaniView Answer on Stackoverflow
Solution 17 - AndroiddugguView Answer on Stackoverflow
Solution 18 - AndroidJaydevView Answer on Stackoverflow
Solution 19 - AndroidMuhaiminur RahmanView Answer on Stackoverflow
Solution 20 - AndroidsutuioncodeView Answer on Stackoverflow
Solution 21 - AndroidDharmendra MishraView Answer on Stackoverflow
Solution 22 - AndroidPankaj LilanView Answer on Stackoverflow
Solution 23 - Androidpruthwiraj.kadamView Answer on Stackoverflow