如何在Android应用程序中显示当前日期和时间?


当前回答

如果您想以特定的模式获取日期和时间,可以使用

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

其他回答

为显示当前日期和时间的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);

检查完整的代码Android -显示当前日期和时间在一个Android Studio示例的源代码

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

}

从如何获得完整的日期与正确的格式?:

请使用

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

获得当前用户设置意义上的有效时间和日期格式(例如12/24时间格式)。

import android.text.format.DateFormat;

private void some() {
    final Calendar t = Calendar.getInstance();
    textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();

实际上,最好使用TextClock小部件。它为您处理所有的复杂性,并将尊重用户的12/24小时的偏好。 http://developer.android.com/reference/android/widget/TextClock.html