Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 544
Anonymous One Avatar asked May 12 '16 10:05

Anonymous One


1 Answers

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:

  • ZoneId
  • ZoneOffset
  • ZoneRules

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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
like image 93
Basil Bourque Avatar answered Sep 19 '22 00:09

Basil Bourque