Display the current time and date in an Android application
Solution 1:
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:
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);
}
}
Solution 3:
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:
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: