Anonymous One
Anonymous One

Reputation: 421

How to get timezone from timezone offset in java?

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

Upvotes: 5

Views: 19887

Answers (2)

Harshit Singhvi
Harshit Singhvi

Reputation: 104

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]);
     }
   }
}

Upvotes: 2

Basil Bourque
Basil Bourque

Reputation: 338201

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?

Upvotes: 3

Related Questions