在 Android 应用程序中显示当前时间和日期
Posted
技术标签:
【中文标题】在 Android 应用程序中显示当前时间和日期【英文标题】:Display the current time and date in an Android application 【发布时间】:2011-01-17 06:52:56 【问题描述】:如何在 android 应用程序中显示当前日期和时间?
【问题讨论】:
【参考方案1】:好的,没有那么难,因为有几种方法可以做到这一点。我假设您想将当前日期和时间放入 TextView
。
String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
在文档中可以轻松找到更多内容here .在那里您可以找到有关如何更改用于转换的格式的更多信息。
【讨论】:
请 - 更加明确!有什么错误?您是否导入了错误的 DateFormat 类?这是java.text.DateFormat
而不是android.text.format.DateFormat
!它是java.util.Date
而不是java.sql.Date
!关于提问的一点提示:尽量准确,例如:在你的问题中声明“显示”的意思。当你输入我的行时——当然,Date 和 DateFormat 都必须被导入——如果每个都可以选择 2,那么你至少可以尝试任何组合:它只有 4!
对不起先生,我得到的是日期而不是时间。同样我们能得到时间吗?
看看developer.android.com/reference/java/text/SimpleDateFormat.html - 在那里你可以看到如何准确地定义你想要在你的输出字符串中的内容。例如。供时间使用"HH:mm:ss"
!完全:currentTimeString = new SimpleDateFormat("HH:mm:ss").format(new Date());
还有DateFormat.getTimeInstance()
和DateFormat.getDateTimeInstance()
。
效率如何?假设您需要从不断触发的方法中获得时间。有什么比每次都创建一个新的 Date 对象更有效的吗?【参考方案2】:
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.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N (24)。 如何声明SimpleDateFormat
因为我找不到符号类【参考方案3】:
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 这个函数是Android SDK自带的,只要你的类扩展Activity就可以了 我知道这是个老问题,但如果有人像我一样在 google 中找到它,他应该知道 Date.getX 方法已被弃用。【参考方案4】:显示时间的明显选择是AnalogClock
View 和DigitalClock
View。
例如下面的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical">
<AnalogClock
android:layout_
android:layout_/>
<DigitalClock
android:layout_
android:layout_
android:gravity="center"
android:textSize="20sp"/>
</LinearLayout>
看起来像这样:
【讨论】:
亲爱的先生,我想使用 setText 显示当前时间。 看完这个明显的答案后,我觉得自己像个傻逼!我实现了我自己的可运行文件,让它在给定的时间内休眠,等等,当明显的答案是一个 XML-one-liner 时!非常感谢(在您发帖后一年多):-) 在 2015 年已弃用,建议您改用 TextClock。 :) AnalogClock 在 API 级别 23 中已弃用。AnalogClock 和 DigitalClock 仅显示当前时间,而不显示当前日期。【参考方案5】:如果你想要一行代码:
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
结果是"2016-09-25 16:50:34"
【讨论】:
【参考方案6】:我自己的工作解决方案:
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) 在它应该是 6 时返回 5?我的设备有正确的时间设置。 哦,是的,但是当其他变量都准确时,为什么他们必须这样做。 :) 日历 c = Calendar.getInstance(); int 月 = c.get(Calendar.MONTH) + 1;字符串 sDate = 月 + "-" + c.get(Calendar.DAY_OF_MONTH) + "-" + c.get(Calendar.YEAR) + "-" + c.get(Calendar.HOUR_OF_DAY) + ":" + c.获取(日历。分钟);效果很好【参考方案7】:如果您想以特定模式获取日期和时间,您可以使用
Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());
【讨论】:
【参考方案8】:来自How to get full date with correct format?:
请使用
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()));
【讨论】:
【参考方案9】:这是对我有用的代码。请试试这个。这是一种从系统调用中获取时间和日期的简单方法。
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;
【讨论】:
【参考方案10】:用途:
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);
【讨论】:
【参考方案11】:String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
使用formattedDate
作为您的String
,并填写日期。
就我而言:mDateButton.setText(formattedDate);
【讨论】:
【参考方案12】:实际上,最好使用 TextClock 小部件。它为您处理所有复杂性,并将尊重用户的 12/24 小时偏好。 http://developer.android.com/reference/android/widget/TextClock.html
【讨论】:
【参考方案13】:显示当前日期函数:
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);
【讨论】:
【参考方案14】: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
【讨论】:
【参考方案15】:这将给出当前日期和时间:
public String getCurrDate()
String dt;
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
return dt;
【讨论】:
【参考方案16】:只需复制此代码,希望它对您有用。
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
【讨论】:
【参考方案17】:String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();
【讨论】:
【参考方案18】:试试下面的代码:
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);
【讨论】:
【参考方案19】:你可以试试这个方法
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());
【讨论】:
【参考方案20】:如果您希望在 android 中使用日期/时间,我建议您使用 ThreeTenABP,它是 java.time.*
包的一个版本(从 android 上的 API 26 开始提供)随 Java 8 一起提供,可替代 @ 987654323@ 和java.util.Calendar
。
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);
【讨论】:
直截了当,我相信您的意思是正确的:java.time 内置来自 Android API 级别 26。ThreeTenABP 是您用来虚拟获取的在较低的 API 级别上具有相同的功能。所以代码可以在低级别和高级别上工作。 由于问题是关于显示日期和时间,为此可以使用ZonedDateTime
代替LocalDate
和DateTimeFormatter.ofLocalizedDateTime
代替@ 987654329@。否则代码将相同。【参考方案21】:
用于在 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 – Display the current date and time in an Android Studio Example with source code
【讨论】:
【参考方案22】:要获取当前的时间/日期,只需使用以下代码 sn-p:
使用时间:
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());
你可以走了。
【讨论】:
【参考方案23】: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";
【讨论】:
以上是关于在 Android 应用程序中显示当前时间和日期的主要内容,如果未能解决你的问题,请参考以下文章
在 SharedPreferences Android 中使用当前日期作为键
Android自学日记使用DatePicker以及TimePicker显示当前日期和时间