如何在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….
其他回答
你也可以使用android.os.SystemClock。 例如,SystemClock.elapsedRealtime()将在手机处于睡眠状态时为您提供更准确的时间读数。
实际上,使用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.
对于当前带格式的日期和时间,使用:
在Java中
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
Log.d("Date", "DATE: " + strDate)
在Kotlin
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
var myDate: String = current.format(formatter)
Log.d("Date", "DATE: " + myDate)
} else {
var date = Date()
val formatter = SimpleDateFormat("MMM dd yyyy HH:mma")
val myDate: String = formatter.format(date)
Log.d("Date", "DATE: " + myDate)
}
日期格式化程序模式
"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
你可以简单地使用下面的代码:
DateFormat df = new SimpleDateFormat("HH:mm"); // Format time
String time = df.format(Calendar.getInstance().getTime());
DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd"); // Format date
String date = df1.format(Calendar.getInstance().getTime());
下面是一些获取时间和日期的方法:
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();
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- 解析日期字符串并更改格式
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- Java SimpleDateFormat("yyyy-MM-dd' t ' hh:mm:ss' z '")给出的时区为IST
- 在Java中转换字符串到日历对象