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


当前回答

您可以从日历中单独获取时间和日期。

// You can pass time zone and Local to getInstance() as parameter

Calendar calendar = Calendar.getInstance();

int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int date = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);

其他回答

Use:

Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour + ":" + time.minute);

例如,这将为您提供“12:32”。

记得导入android.text.format.Time;。

你可以使用以下代码:

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

输出:

2014-11-11 00:47:55

您还可以从这里获得SimpleDateFormat的更多格式化选项。

这是一个获取日期和时间的有用方法:

private String getDate(){
    DateFormat dfDate = new SimpleDateFormat("yyyy/MM/dd");
    String date=dfDate.format(Calendar.getInstance().getTime());
    DateFormat dfTime = new SimpleDateFormat("HH:mm");
    String time = dfTime.format(Calendar.getInstance().getTime());
    return date + " " + time;
}

你可以调用这个方法来获取当前的日期和时间值:

2017/01//09 19:23

要获取当前时间,您可以使用System.currentTimeMillis(),这是Java中的标准。然后您可以使用它来创建日期

Date currentDate = new Date(System.currentTimeMillis());

正如其他人提到的创造一个时间

Time currentTime = new Time();
currentTime.setToNow();

你可以使用下面的代码获取当前的日期和时间:

val current_data_time= SimpleDateFormat("MMMMddyyyyHHmm", Locale.getDefault())
val currentDateandTime: String = current_data_time.format(Date())

如果你用MMMM:那么月份名称就会显示出来。“3”

如果你用MM:那么数字显示。“3”

Dd表示日,yyyy表示年

如果你只想要最后两位数字,那么yy。

如果你先改变月份和年份,然后需要左右改变MMMM、dd和yyyy,例如:12/3/2021 12:12 dd/MM/ yyyy HH: MM