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


当前回答

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

其他回答

试试下面的方法。下面给出了所有格式以获得日期和时间格式。

    Calendar c = Calendar.getInstance();
    SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa");
    String datetime = dateformat.format(c.getTime());
    System.out.println(datetime);

SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");


String currentDateandTime = databaseDateTimeFormate.format(new Date());     //2009-06-30 08:29:36
String currentDateandTime = databaseDateFormate.format(new Date());     //2009-06-30
String currentDateandTime = sdf1.format(new Date());     //30.06.09
String currentDateandTime = sdf2.format(new Date());     //2009.06.30 AD at 08:29:36 PDT
String currentDateandTime = sdf3.format(new Date());     //Tue, Jun 30, '09
String currentDateandTime = sdf4.format(new Date());     //8:29 PM
String currentDateandTime = sdf5.format(new Date());     //8:29
String currentDateandTime = sdf6.format(new Date());     //8:28:36:249
String currentDateandTime = sdf7.format(new Date());     //8:29 AM,PDT
String currentDateandTime = sdf8.format(new Date());     //2009.June.30 AD 08:29 AM

日期格式

G   Era designator (before christ, after christ)
y   Year (e.g. 12 or 2012). Use either yy or yyyy.
M   Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d   Day in month. Number of d's determine length of format (e.g. d or dd)
h   Hour of day, 1-12 (AM / PM) (normally hh)
H   Hour of day, 0-23 (normally HH)
m   Minute in hour, 0-59 (normally mm)
s   Second in minute, 0-59 (normally ss)
S   Millisecond in second, 0-999 (normally SSS)
E   Day in week (e.g Monday, Tuesday etc.)
D   Day in year (1-366)
F   Day of week in month (e.g. 1st Thursday of December)
w   Week in year (1-53)
W   Week in month (0-5)
a   AM / PM marker
k   Hour in day (1-24, unlike HH's 0-23)
K   Hour in day, AM / PM (0-11)
z   Time Zone

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

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

实际上,使用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.

博士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….