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


当前回答

Use:

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

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

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

其他回答

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

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

你可以用:

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

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

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

检查Calendar类文档。

Android中的当前时间和日期格式

Calendar c = Calendar.getInstance();
System.out.println("Current dateTime => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate = df.format(c.getTime());
System.out.println("Format dateTime => " + formattedDate);

输出

I/System.out: Current dateTime => Wed Feb 26 02:58:17 GMT+05:30 2020
I/System.out: Format dateTime => 26-02-2020 02:58:17 AM

对于当前日期和时间,使用:

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

输出:

Feb 27, 2012 5:41:23 PM
    //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);