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


当前回答

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

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

其他回答

下面是一些获取时间和日期的方法:

public static void getCurrentTimeUsingDate() {
    Date date = new Date();
    String strDateFormat = "hh:mm:ss a";
    DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
    String formattedDate= dateFormat.format(date);
    Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
}

使用日历的时间

public static void getCurrentTimeUsingCalendar() {
    Calendar cal = Calendar.getInstance();
    Date date=cal.getTime();
    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    String formattedDate=dateFormat.format(date);
    Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
}

当地时间日期

public static void getCurrentTime(){
    System.out.println("-----Current time of your time zone-----");
    LocalTime time = LocalTime.now();
    Toast.makeText(this, time, Toast.LENGTH_SHORT).show();
}

分区时间

public static void getCurrentTimeWithTimeZone(){
    Toast.makeText(this, "Current time of a different time zone using LocalTime", Toast.LENGTH_SHORT).show();

    ZoneId zoneId = ZoneId.of("America/Los_Angeles");
    LocalTime localTime=LocalTime.now(zoneId);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    String formattedTime=localTime.format(formatter);
    Toast.makeText(this,formattedTime , Toast.LENGTH_SHORT).show();
}

获取当前时间和日期的简单方法

import java.util.Calendar

Date currentTime = Calendar.getInstance().getTime();
Time now = new Time();
now.setToNow();

试试这个对我也有用。

Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();

你可以使用以下代码:

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的更多格式化选项。

在com.google.gson.internal.bind.util包中有一个ISO8601Utils实用程序类,所以如果你在你的应用程序中使用Gson,你可以使用它。

它支持毫秒和时区,所以这是一个很好的开箱即用的选择。