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


当前回答

试着用简单的方法获取当前的日期和时间:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
String currentDateandTime = sdf.format(new Date());

其他回答

你也可以使用android.os.SystemClock。 例如,SystemClock.elapsedRealtime()将在手机处于睡眠状态时为您提供更准确的时间读数。

一件容易的事。您可以剖析时间,以获得当前时间的单独值,如下所示:

Calendar cal = Calendar.getInstance();

int millisecond = cal.get(Calendar.MILLISECOND);
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);

// 12-hour format
int hour = cal.get(Calendar.HOUR);

// 24-hour format
int hourofday = cal.get(Calendar.HOUR_OF_DAY);

日期也一样,如下所示:

Calendar cal = Calendar.getInstance();

int dayofyear = cal.get(Calendar.DAY_OF_YEAR);
int year = cal.get(Calendar.YEAR);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
int dayofmonth = cal.get(Calendar.DAY_OF_MONTH);

对于后缀为“AM”或“PM”的12小时时钟:

DateFormat df = new SimpleDateFormat("KK:mm:ss a, dd/MM/yyyy", Locale.getDefault());
String currentDateAndTime = df.format(new Date());

对于带有“AM”或“PM”后缀的24小时时钟:

 DateFormat df = new SimpleDateFormat("HH:mm:ss a, dd/MM/yyyy", Locale.getDefault());
 String currentDateAndTime = df.format(new Date());

要删除后缀,只需删除以时间格式书写的“a”。

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

您应该根据新的API使用calendar类。Date类现在已弃用。

Calendar cal = Calendar.getInstance();

String date = "" + cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR);

String time = "" + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE);