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


当前回答

你可以用:

import java.util.Calendar;
import java.util.Date;

Date currentTime = Calendar.getInstance().getTime();

Calendar中有许多常量可以满足您的所有需要。

检查Calendar类文档。

其他回答

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

试试这个对我也有用。

    //currentTimeMillis is System.currentTimeMillis()

    long totalSeconds = currentTimeMillis / 1000;
    int currentSecond = (int)totalSeconds % 60;

    long totalMinutes = totalSeconds / 60;
    int currentMinute = (int)totalMinutes % 60;

    long totalHours = totalMinutes / 60;
    int currentHour = (int)totalHours % 12;

    TextView tvTime = findViewById(R.id.tvTime);
    tvTime.setText((currentHour + OR - TIME YOU ARE FROM GMT) + ":" + currentMinute + ":" + currentSecond);

你可以通过这个函数得到你的当地时间和GMT时间

public String getCurrentDate() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd hh:mm a zzz");
    Date date = new Date();
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+6:00"));
    return sdf.format(date);
}

要获取当前时间,您可以使用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