[英]elapsed time using System.currentTimeMillis not working on android
[英]Get absolute time using result of System.currentTimeMillis in android
我定义了 BuildConfig 字段以用作应用程序版本。
buildConfigField "long", "BUILDTIME", System.currentTimeMillis() + "L"
而且我可以在我的 MainActivity 中正确地获取该值。
binding.buttonTest.text = "Build Version is: " + SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA)
.format(BuildConfig.BUILDTIME)
但是在测试手机和具有不同时区的 AVD 上测试我的应用程序时,
SimpleDateFormat 返回的字符串不相同。
- 结果 -
测试手机:Build Version是:20220502172527
AVD:构建版本是:20220502082738
我认为这是因为 SimpleDateFormat 给出了相对时间,而不是绝对时间。
如何通过 System.currentTimeMillis() 的结果获得 android 中的绝对时间?
谢谢。
注意:我不想使用 Date(),因为它的所有 get 方法都已弃用。
您似乎不关心小数秒,因此使用自 1970-01-01T00:00Z 纪元参考以来的整秒计数。
Instant
.now()
.getEpochSecond()
生成文本。
Instant
.ofEpochSecond(
mySavedCountOfSecondsFromEpoch
) // Returns an `Instant`.
.atOffset(
ZoneOffset.UTC
) // Returns an `OffsetDateTime`.
.format(
DateTimeFormatter
.ofPattern( "uuuuMMddHHmmss" )
) // Returns a `String`.
20220501123456
您正在使用多年前被现代java.time类取代的糟糕日期时间类。
Android 26+ 包括一个实现。 对于早期的 Android,最新的工具通过“API 脱糖”带来了大部分功能。
Instant
对System.currentTimeMillis()
的调用可以替换为Instant.now().toEpochMilli()
。
解析从 UTC 中看到的 1970 年第一时刻的纪元参考以来的毫秒数。
Instant instant = Instant.ofEpochMilli( myMillis ) ;
OffsetDateTime
为了更灵活地生成文本,请将基本构建块Instant
class 转换为OffsetDateTime
。
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
DateTimeFormatter
定义格式化模式。
请注意,您想要的格式会导致数据丢失,因为会去掉小数秒。
不需要您传递的语言环境。 在您想要的格式中,没有什么需要本地化。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
生成文本。
String output = odt.format( f ) ;
您需要指定您的TimeZone
SimpleDateFormat
使用setTimeZone(TimeZone.UTC)
的时区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.