Android Timezone get default returning wrong value

Viewed 58

i have an application. I want to get phone's time as long value. Although the phone's timezone is UTC+3, UTC 0 is displayed in all the following operations. I think app locale is wrong.

Phone Time is : 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

How can I get right timezone?

1 Answers

If you want the current millis, simply use an Instant, get the current moment by using Instant.now() and receive the value in milliseconds via Instant.now().toEpochMilli(). You can use that value in order to display date and time depending on a ZoneId or ZoneOffset, which may be the systemDefault() or any given one.

Here's an example in 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 (about a minute ago):

Current millis: 1663143809106
2022-09-14T08:23:29.106785Z[UTC]
2022-09-14T11:23:29.106785+03:00[Europe/Istanbul]

The millis (resp. Instants) are independent from any zone or offset and you can use them to display different datetimes based on the same Instant.

Related