1

How do I get the timezone offset in android - java? an error in local date-time appears.

 public static String getOffsetTimeZone() {
    TimeZone timeZone = TimeZone.getDefault();
    Timber.e(": %s", timeZone.getOffset(Calendar.ZONE_OFFSET));
    Timber.e(" timeZone.getID(): %s", timeZone.getID());

    String myTimeZone = ZoneId.systemDefault().getId();
    LocalDateTime dt = LocalDateTime.now();
    LocalDate dt0 = LocalDate.now(); // Added 1.8


    ZoneId zone = ZoneId.of(myTimeZone);
    ZonedDateTime zdt = dt.atZone(zone);
    ZoneOffset offset = zdt.getOffset();
    int secondsOfHour = offset.getTotalSeconds() % (60 * 60);
    String out = String.format("%35s %10s%n"," zone= "+ zone," offset= "+ offset);
    Timber.e("out= " + out);
    return "UTC";
}

2 Answers2

4

You can simply use the following to get it. This will get you your current offset.

Integer offset  = ZonedDateTime.now().getOffset().getTotalSeconds();
che10
  • 2,176
  • 2
  • 4
  • 11
3

tl;dr

ZoneId
.systemDefault()
.getRules()
.getOffset(
    Instant.now()
)

Details

Never use TimeZone. That class is one of the legacy date-time classes bundled with the earliest versions of Java. Supplanted years ago by the modern java.time classes defined in JSR 310.

Never call LocalDateTime.now(). That class cannot represent a moment as it purposely lacks any concept of time zone or offset from UTC. I cannot imagine a scenario where calling that method would be the right thing to do.

Get your JVM’s current default time zone.

ZoneId zone = ZoneId.systemDefault() ;

Get the rules for that zone, the history of past, present, and future changes to the offset used by the people of that particular region.

ZoneRules rules = zone.getRules() ;

Capture the current moment.

Instant instant = Instant.now() ;

Get the offset in effect at that moment in that zone, producing a ZoneOffset.

ZoneOffset offset = rules.getOffset( instant ) ;

The java.time classes are present in Android 26 and later. For earlier Android, modern tooling provides most of the functionality via “API desugaring”.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154