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


当前回答

博士tl;

Instant.now()  // Current moment in UTC.

…or…

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

细节

其他答案虽然正确,但已经过时了。旧的日期时间类已被证明设计得很糟糕,令人困惑和麻烦。

java.time

那些旧的类已经被java所取代。时间框架。

Java 8及以后版本:Java。内置时间框架。 Java 7和6:使用Java .time的后端端口。 Android:使用后端口的包装版本。

这些新类的灵感来自于非常成功的Joda-Time项目,该项目由JSR 310定义,并由three10 - extra项目扩展。

请参阅Oracle教程。

即时

一个瞬间是UTC时间轴上的一个时刻,分辨率可达纳秒。

 Instant instant = Instant.now(); // Current moment in UTC.

时区

应用一个时区(ZoneId)来获得一个zoneeddatetime。如果省略时区,则隐式应用JVM的当前默认时区。最好显式地指定所需/预期的时区。

使用大洲/地区格式的正确时区名称,如美洲/蒙特利尔、欧洲/布鲁塞尔或亚洲/加尔各答。不要使用3-4个字母的缩写,如EST或IST,因为它们既不规范也不独特。

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

生成字符串

您可以很容易地生成一个String作为日期-时间值的文本表示。您可以使用标准格式、自己的自定义格式或自动本地化的格式。

ISO 8601

您可以调用toString方法来使用通用且合理的ISO 8601标准来格式化文本。

String output = instant.toString();

2016 - 03 - 23 - t03:09:01.613z

注意,对于ZonedDateTime, toString方法通过在方括号中附加时区名称来扩展ISO 8601标准。非常有用和重要的信息,但不标准。

2016 - 03 - 22 - t20:09:01.613喂饲(美国/ Los_Angeles)

自定义格式

或者使用DateTimeFormatter类指定自己的特定格式化模式。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

为人类语言(英语、法语等)指定一个区域设置,用于翻译日/月的名称,以及定义年、月和日期顺序等文化规范。注意Locale与时区无关。

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

本地化

更好的是,让java。时间做自动本地化的工作。

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

关于java.time

java。时间框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期-时间类,如java.util。日期,日历和简单日期格式。

要了解更多,请参阅Oracle教程。搜索Stack Overflow可以找到很多例子和解释。规范是JSR 310。

Joda-Time项目现在处于维护模式,建议迁移到java。时间类。

你可以交换java。Time对象直接使用数据库。使用符合JDBC 4.2或更高版本的JDBC驱动程序。不需要字符串,不需要java。sql。*类。Hibernate 5和JPA 2.2支持java.time。

哪里可以java。获得时间类?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation. Java 9 brought some minor features and fixes. Java SE 6 and Java SE 7 Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport. Android Later versions of Android (26+) bundle implementations of the java.time classes. For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android. If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

其他回答

实际上,使用time . getcurrenttimezone()在设备上设置当前时区更安全,否则您将获得UTC的当前时间。

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();

然后,你可以得到你想要的所有日期字段,例如:

textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
textViewMonth.setText(today.month + "");              // Month (0-11)
textViewYear.setText(today.year + "");                // Year 
textViewTime.setText(today.format("%k:%M:%S"));  // Current time

详情请参阅android.text.format.Time类。

更新

正如许多人指出的那样,谷歌说这个类有一些问题,不应该再使用了:

This class has a number of issues and it is recommended that GregorianCalendar is used instead. Known issues: For historical reasons when performing time calculations all arithmetic currently takes place using 32-bit integers. This limits the reliable time range representable from 1902 until 2037.See the wikipedia article on the Year 2038 problem for details. Do not rely on this behavior; it may change in the future. Calling switchTimezone(String) on a date that cannot exist, such as a wall time that was skipped due to a DST transition, will result in a date in 1969 (i.e. -1, or 1 second before 1st Jan 1970 UTC). Much of the formatting / parsing assumes ASCII text and is therefore not suitable for use with non-ASCII scripts.

如果你想以特定的模式获取日期和时间,你可以使用以下命令:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());

Or,

日期:

String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());

时间:

String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());

Use:

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

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

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

你可以通过这个函数得到你的当地时间和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);
}

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

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