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


当前回答

使用实例显示当前日期函数。

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

其他回答

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中使用日期/时间,我建议你使用ThreeTenABP,这是java.time的一个版本。*包(可从android上的API 26开始使用)随Java 8一起发布,可作为Java .util. date和Java .util. calendar的替代品。

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); 

使用formattedDate作为填充日期的字符串。 在我的情况下:mDateButton.setText(formattedDate);

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

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

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

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

简单地复制此代码,并希望这为您工作良好。

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