How to get timezone from timezone offset in java?

14,570

Solution 1

Use TimeZone#getAvailableIDs(int)

import java.util.*;
class Hello
{
   public static void main (String[] args) throws java.lang.Exception
   {
     TimeZone tz = TimeZone.getDefault();
     int offset = 21600000;
     String[] availableIDs = tz.getAvailableIDs(offset);
     for(int i = 0; i < availableIDs.length; i++) {
       System.out.println(availableIDs[i]);
     }
   }
}

Solution 2

tl;dr

Instant instant = Instant.now();
List < String > names =
        ZoneId
                .getAvailableZoneIds()
                .stream()
                .filter(
                        ( String name ) ->
                                ZoneId
                                        .of( name )
                                        .getRules()
                                        .getOffset( instant )
                                        .equals(
                                                ZoneOffset.ofHours( 6 )
                                        )
                )
                .collect( Collectors.toList() )
;

In Java 14.0.1:

names = [Asia/Kashgar, Etc/GMT-6, Asia/Almaty, Asia/Dacca, Asia/Omsk, Asia/Dhaka, Indian/Chagos, Asia/Qostanay, Asia/Bishkek, Antarctica/Vostok, Asia/Urumqi, Asia/Thimbu, Asia/Thimphu]

java.time

The modern solution uses the java.time classes that years ago supplanted the terrible legacy date-time classes. Specifically, TimeZone was replaced by:

An offset-from-UTC is merely a number of hours-minutes-seconds ahead of or behind the prime meridian. A time zone is much more. A time zone is a history fo the past, present, and future changes to the offset used by the people of a particular region. A time zone has a name in Continent/Region format. See list of zones.

Get the JVM’s current time zone.

ZoneId z = ZoneId.systemDefault() ;

Get a list of all ZoneId objects currently defined. Be aware that time zones are frequently changed by politicians. So this list, and the rules they contain, will change. Keep your tzdata up-to-date.

Set< String > zones = ZoneId.getAvailableZoneIds() ;

You asked:

I want to know how to get the timezone name from timezone offset.

Many time zones may coincidentally share the same offset at any given moment. In code below, we loop all known time zones, asking each for its offset.

Since time zone rules change over time (determined by politicians), you must provide a moment for which you want the offset in use by each zone. Here we use the current moment at runtime.

// Convert your milliseconds to an offset-from-UTC.
int milliseconds = 21_600_000;
int seconds = Math.toIntExact( TimeUnit.MILLISECONDS.toSeconds( milliseconds ) );
ZoneOffset targetOffset = ZoneOffset.ofTotalSeconds( seconds );

// Capture the current moment as seen in UTC (an offset of zero hours-minutes-seconds).
Instant now = Instant.now();

// Loop through all know time zones, comparing each one’s zone to the target zone.
List < ZoneId > hits = new ArrayList <>();
Set < String > zoneNames = ZoneId.getAvailableZoneIds();
for ( String zoneName : zoneNames )
{
    ZoneId zoneId = ZoneId.of( zoneName );

    ZoneRules rules = zoneId.getRules();
    // ZoneRules rules = zoneId.getRules() ;
    ZoneOffset offset = rules.getOffset( now );
    if ( offset.equals( targetOffset ) )
    {
        hits.add( zoneId );
    }
}

Dump to console. See this code run live at IdeOne.com.

// Report results.
System.out.println( "java.version " + System.getProperty("java.version") ) ;
System.out.println( "java.vendor " + System.getProperty("java.vendor") ) ;
System.out.println() ;
System.out.println( "targetOffset = " + targetOffset );
System.out.println( "hits: " + hits );

See this code run live at IdeOne.com.

java.version 12.0.1

java.vendor Oracle Corporation

targetOffset = +06:00

hits: [Asia/Kashgar, Etc/GMT-6, Asia/Almaty, Asia/Dacca, Asia/Omsk, Asia/Dhaka, Indian/Chagos, Asia/Qyzylorda, Asia/Bishkek, Antarctica/Vostok, Asia/Urumqi, Asia/Thimbu, Asia/Thimphu]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Share:
14,570
Anonymous One
Author by

Anonymous One

BY DAY: Alt-Rock Ninja Cowgirl at Veridian Dynamics. BY NIGHT: I write code and code rights for penalcoders.example.org, an awesome non-profit that will totally take your money at that link. My kids are cuter than yours. FOR FUN: C+ Jokes, Segway Roller Derby, NYT Sat. Crosswords (in Sharpie!), Ostrich Grooming. "If you see scary things, look for the helpers-you'll always see people helping."-Fred Rogers

Updated on June 20, 2022

Comments

  • Anonymous One
    Anonymous One almost 2 years

    I know how to get the opposite. That is given a timezone I can get the timezone offset by the following code snippet:

    TimeZone tz = TimeZone.getDefault();
    System.out.println(tz.getOffset(System.currentTimeMillis()));
    

    I want to know how to get the timezone name from timezone offset.

    Given,

    timezone offset = 21600000 (in milliseconds; +6.00 offset)

    I want to get result any of the following possible timezone names:

    (GMT+6:00) Antarctica/Vostok
    (GMT+6:00) Asia/Almaty
    (GMT+6:00) Asia/Bishkek
    (GMT+6:00) Asia/Dacca
    (GMT+6:00) Asia/Dhaka
    (GMT+6:00) Asia/Qyzylorda
    (GMT+6:00) Asia/Thimbu
    (GMT+6:00) Asia/Thimphu
    (GMT+6:00) Asia/Yekaterinburg
    (GMT+6:00) BST
    (GMT+6:00) Etc/GMT-6
    (GMT+6:00) Indian/Chagos
    
  • Anonymous One
    Anonymous One about 8 years
    That's nice! Are there any pitfalls using this strategy? I mean DST (Daylight Saving Time) related things?
  • Harshit Singhvi
    Harshit Singhvi about 8 years
  • Anonymous One
    Anonymous One about 8 years
    Thank you very much for your time.
  • Matt Johnson-Pint
    Matt Johnson-Pint about 8 years
    Be aware that this only returns entries whose standard time offset matches. For example, passing -25200000 doesn't return America/Los_Angeles, which uses that offset during daylight saving time.
  • Jon Skeet
    Jon Skeet about 8 years
    Why are you using TimeZone.getDefault() at all? This code would be better as String[] ids = TimeZone.getAvailableIds(21600000L);. Avoid calling static methods as if they were instance methods.
  • Anonymous One
    Anonymous One about 8 years
    Thank you @JonSkeet. And thank you. Matt Johnson. Your comments are useful.
  • Anonymous One
    Anonymous One about 8 years
    One question, if I change the default timezone from one thread will it affect other threads? @JonSkeet
  • Jon Skeet
    Jon Skeet about 8 years
    @AnonymousOne: I believe so, yes.
  • Jimmy
    Jimmy over 6 years
    Why don't we use sun.util.calendar.ZoneInfo offset = (ZoneInfo) timezone.getDefault(); directly? It will give us timezone info directly like "Asia/Almaty" by .getID() method.