[英]Android Timezone get default returning wrong value
我有一個應用程序。 我想將手機的時間作為長期價值。 雖然手機的時區是UTC+3,但在后面的所有操作中都會顯示UTC 0。 我認為應用程序語言環境是錯誤的。
電話時間是:10.46
TimeZone.getDefault().id // return UTC
Date() // Wed Sep 14 07:46:57 UTC 2022
LocalDateTime().now() // 2022-09-14T07:46:22.849
Timestamp(System.currentTimeMillis()) // 2022-09-14 07:50:18.153
我怎樣才能獲得正確的時區?
如果您想要當前毫秒,只需使用Instant
,使用Instant.now()
獲取當前時刻並通過Instant.now().toEpochMilli()
以毫秒為單位接收值。 您可以使用該值來根據ZoneId
或ZoneOffset
顯示日期和時間,這可能是 systemDefault systemDefault()
或任何給定的。
這是 Java 中的一個示例:
public static void main(String[] args) {
// get the current moment
Instant now = Instant.now();
// and print its epoch millis
System.out.println("Current millis: " + now.toEpochMilli());
// then create two different time zones (ZoneId in java.time)
ZoneId utc = ZoneId.of("UTC");
ZoneId ankara = ZoneId.of("Europe/Istanbul");
// then create different (!) datetimes using the same instant but different zones
ZonedDateTime utcZdt = ZonedDateTime.ofInstant(now, utc);
ZonedDateTime ankaraZdt = ZonedDateTime.ofInstant(now, ankara);
// print them
System.out.println(utcZdt);
System.out.println(ankaraZdt);
}
Output(大約一分鍾前):
Current millis: 1663143809106
2022-09-14T08:23:29.106785Z[UTC]
2022-09-14T11:23:29.106785+03:00[Europe/Istanbul]
Millis (resp. Instant
s) 獨立於任何區域或偏移量,您可以使用它們基於相同的Instant
顯示不同的日期時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.