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

发布于 2024-08-21 21:00:15 字数 34 浏览 8 评论 0原文

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

How do I display the current date and time in an Android application?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

拥有 2024-08-28 21:00:15

好吧,没那么难,因为有几种方法可以做到这一点。我假设你想把当前日期&将时间放入 TextView 中。

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

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

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

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.

走过海棠暮 2024-08-28 21:00:15
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);
    }

}

在此处输入图像描述

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

眼眸里的那抹悲凉 2024-08-28 21:00:15
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){
                }
            }
    }
}
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){
                }
            }
    }
}
兔小萌 2024-08-28 21:00:15

显示时间的明显选择是 AnalogClock ViewDigitalClock查看

例如,以下布局:

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

看起来像这样:

屏幕截图

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:

screenshot

笛声青案梦长安 2024-08-28 21:00:15

如果您想要一行代码:

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

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

In case you want a single line of code:

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

The result is "2016-09-25 16:50:34"

终遇你 2024-08-28 21:00:15

我自己的工作解决方案:

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

希望这有帮助!

My own working solution:

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

Hope this helps!

灼疼热情 2024-08-28 21:00:15

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

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

If you want to get the date and time in a specific pattern you can use

Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());
天暗了我发光 2024-08-28 21:00:15

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

请,用于

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

From How to get full date with correct format?:

Please, use

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

to get valid time and date formats in sense of current user settings (12/24 time format, for example).

import android.text.format.DateFormat;

private void some() {
    final Calendar t = Calendar.getInstance();
    textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}
泪是无色的血 2024-08-28 21:00:15

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

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

Here is the code which worked for me. Please try this. It is a simple method which takes time and date from a system call.

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;
}
无远思近则忧 2024-08-28 21:00:15

使用:

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

Use:

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);
云之铃。 2024-08-28 21:00:15
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

使用 formattedDate 作为填充日期的 String
就我而言:mDateButton.setText(formattedDate);

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

Use formattedDate as your String filled with the date.
In my case: mDateButton.setText(formattedDate);

乱世争霸 2024-08-28 21:00:15

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

Actually, you're best off with the TextClock widget. It handles all of the complexity for you and will respect the user's 12/24hr preferences.
http://developer.android.com/reference/android/widget/TextClock.html

绝不放开 2024-08-28 21:00:15

要显示当前日期函数:

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

To display the current date function:

Calendar c = Calendar.getInstance();

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

You must want to import

import java.text.SimpleDateFormat;
import java.util.Calendar;

You must want to use

TextView Date;
Date = (TextView) findViewById(R.id.Date);
吃→可爱长大的 2024-08-28 21:00:15
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

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

This will give date time format like
2010-05-24T18:13:00

蔚蓝源自深海 2024-08-28 21:00:15

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

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}

This would give the current date and time:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}
煞人兵器 2024-08-28 21:00:15

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

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());

Simply copy this code and hope this works fine for you.

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
菩提树下叶撕阳。 2024-08-28 21:00:15
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();
眸中客 2024-08-28 21:00:15

尝试下面的代码:

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

Try the below code:

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);
沐歌 2024-08-28 21:00:15

你可以尝试这个方法

Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());

You Can try this way

Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());
帥小哥 2024-08-28 21:00:15

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

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);

If you wish to work with date/time in android I recommend you to use ThreeTenABP which is a version of java.time.* package (available starting from API 26 on android) shipped with Java 8 available as a replacement for java.util.Date and java.util.Calendar.

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);
七禾 2024-08-28 21:00:15

在 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 示例中显示当前日期和时间

For Show Current Date and Time on 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 – Display the current date and time in an Android Studio Example with source code

萤火眠眠 2024-08-28 21:00:15

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

使用时间

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

就可以了。

To get current Time/Date just use following code snippet:

To use Time:

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

To use Date:

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

and you are good to go.

我喜欢麦丽素 2024-08-28 21:00:15
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";
}
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";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文