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

209

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

23个回答

310

这并不难,有几种方法可以实现。我假设你想将当前日期和时间放入一个 TextView 中。

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

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

在此处可以轻松找到更多文档内容进行阅读,点击这里。那里会提供更多有关如何更改转换格式的信息。


43
请更明确!出了什么错误?您导入了错误的DateFormat类吗?它应该是 java.text.DateFormat 而不是 android.text.format.DateFormat!另外,是 java.util.Date 而不是 java.sql.Date!提问时的一点提示:请尽量准确地说明问题,例如:在问题中声明您所指的“显示”意味着什么。当您键入我的代码行时 - 必须导入Date和DateFormat - 如果每个都有2个选择,您至少可以尝试任何组合:只有4种可能! - Zordid
抱歉,先生,我得到了日期而不是时间。同样,我们能获取时间吗? - BIBEKRBARAL
2
还有DateFormat.getTimeInstance()DateFormat.getDateTimeInstance() - Felix
1
这个有多高效呢?假设你需要从一个不断触发的方法中获取时间。有没有比每次创建一个新的Date对象更有效的方法? - keshav.bahadoor

126
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


2
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N (24)安卓操作系统版本不低于 N 版本(24)。 - kangear
如何声明“SimpleDateFormat”,因为我得到了“找不到符号类”的错误。 - dubis

52
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){
                }
            }
    }
}

@Harshit 只要你的类继承自 Activity,这个函数就随着 Android SDK 一起提供了。 - Carlos P
2
我知道这是一个老问题,但如果有人像我一样在谷歌上找到它,他应该知道方法Date.getX已经被弃用了。 - tobi

42

显示时间的明显选择是 AnalogClock 视图DigitalClock 视图

例如,以下布局:

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

看起来像这样:

screenshot


4
亲爱的先生,我想使用setText显示当前时间。 - BIBEKRBARAL
5
读完这个显而易见的答案后,我感觉自己像个傻瓜!在我实现自己的可运行程序,并让它睡眠一段时间等等之后,显然的答案是一个XML一行代码!非常感谢(在你发布帖子一年多之后) :-) - dbm
6
2015年时这个已经被弃用了,建议您使用TextClock代替。 :) - Evilripper
1
AnalogClock在API 23级中已被弃用。而且,AnalogClock和DigitalClock仅显示当前时间,而不是当前日期。 - Zafer

36

如果您只需要一行代码:

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

结果为"2016-09-25 16:50:34"


22

我的解决方案:

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);
希望这能有所帮助!

我想知道为什么c.get(Calendar.MONTH)返回5,而不是应该的6?我的设备时间设置正确。 - Kris
哦,是啊,但是其他变量都是准确的,他们为什么要这样做呢。 :) - Kris
1
日历 c = Calendar.getInstance(); int 月份 = c.get(Calendar.MONTH) + 1; String s日期 = 月份 + "-" + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.YEAR) + "-" + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE);这个代码可以正常运行。 - user577732

20

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

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

14

来自如何获取正确格式的完整日期?

请使用以下代码:

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

11

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

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

8

使用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接