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


当前回答

下面是对我有用的代码。请尝尝这个。这是一个简单的方法,从系统调用中获取时间和日期。

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

其他回答

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

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

这将给出当前的日期和时间:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}
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);

这将给出日期时间格式 2010 - 05 - 24 - t18:13:00

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

显示时间的明显选择是类比时钟视图(AnalogClock View)和数字时钟视图(DigitalClock View)。

例如,如下布局:

<?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>

看起来是这样的: