208

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

4

23 回答 23

308

好的,并不难,因为有几种方法可以做到这一点。我假设您想将当前日期和时间放入TextView.

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

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

可在此处轻松找到的文档中有更多内容可供阅读 。在那里,您将找到有关如何更改用于转换的格式的更多信息。

于 2010-02-16T07:44:44.293 回答
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);
    }

}

在此处输入图像描述

于 2011-11-04T10:58:45.877 回答
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){
                }
            }
    }
}
于 2010-07-21T10:39:38.960 回答
41

显示时间的明显选择是AnalogClockViewDigitalClockView

例如,以下布局:

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

看起来像这样:

截屏

于 2010-02-16T09:01:28.937 回答
36

如果您想要一行代码:

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

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

于 2016-09-25T13:20:52.540 回答
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);

希望这可以帮助!

于 2011-06-08T11:43:09.230 回答
20

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

Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());
于 2012-01-29T06:15:30.963 回答
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()));
}
于 2011-10-27T21:06:33.347 回答
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;
}
于 2014-05-12T07:30:00.113 回答
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);
于 2014-07-22T05:10:41.937 回答
7
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

用作formattedDateString填写的日期。
就我而言:mDateButton.setText(formattedDate);

于 2013-09-24T11:53:14.690 回答
7

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

于 2014-05-02T15:25:04.250 回答
7

显示当前日期函数:

Calendar c = Calendar.getInstance();

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

您必须要导入

导入 java.text.SimpleDateFormat;导入 java.util.Calendar;

您必须要使用

TextView Date;
Date = (TextView) findViewById(R.id.Date);
于 2017-01-15T05:55:23.587 回答
6
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-24T18:13:00

于 2012-03-14T04:59:03.113 回答
5

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

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}
于 2011-07-27T11:04:34.957 回答
5

只需复制此代码,并希望这对您有用。

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
于 2015-07-20T08:10:22.800 回答
3

试试下面的代码:

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);
于 2013-04-24T09:29:02.000 回答
3
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();
于 2017-01-30T09:54:35.970 回答
3

你可以试试这个方法

Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());
于 2018-06-09T08:53:48.437 回答
2

如果您希望在 android 中使用日期/时间,我建议您使用ThreeTenABP,它是java.time.*Java 8 附带的软件包版本(从 android 上的 API 26 开始提供),可替代java.util.Datejava.util.Calendar.

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);
于 2019-12-16T13:54:18.887 回答
1

在 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 – 在带有源代码的 Android Studio 示例中显示当前日期和时间

于 2018-03-08T06:17:41.650 回答
0

要获取当前时间/日期,只需使用以下代码片段:

使用时间

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

使用日期

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

你很高兴。

于 2017-10-16T07:51:04.033 回答
0
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";
}
于 2018-03-12T06:54:30.323 回答