Harish
Harish

Reputation: 3483

Timezone display in java

I need to display timezone in the following format in my UI.

(GMT -05:00) Eastern Time(US & Canada).

I tried getting the current time and timezone from calendar. But when i tried to get the display name from timezone it just displays as "Eastern time". I am not getting the format mentioned above. Can anyone help.

Following is my code snippet and i am using JDK 1.4.2.

Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
String s = tz.getDisplayName();

Upvotes: 2

Views: 4912

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 340158

java.time

Specify a proper time zone name in the format of Region/City, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/New_York" ) ;

Get the standard name of the time zone.

String outputStandardName = z.toString() ;

America/New_York

Get the descriptive display name of the zone.

String outputDisplayName = z.getDisplayName( TextStyle.FULL_STANDALONE , Locale.US ) ;

Eastern Time

Get the offset-from-UTC (a number of hours-minutes-seconds) currently in use by people in that region. Go through the ZoneRules class.

ZoneRules rules = z.getRules() ;
ZoneOffset offset = rules.getOffset( Instant.now() ) ; // Get current offset.

offset.toString(): -05:00

See this code run live at IdeOne.com.

Upvotes: 1

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51565

Here's the long getDisplayName() method invocation. Try specifying TimeZone.LONG for the style. The method hasn't changed since Java 1.2

getDisplayName

public final String getDisplayName(boolean daylight, int style, Locale locale)

Returns a name of this time zone suitable for presentation to the user in the default locale. If the display name is not available for the locale, then this method returns a string in the normalized custom ID format.

Parameters:

   daylight - if true, return the daylight savings name.
   style - either LONG or SHORT 
   locale - the locale in which to supply the display name.

Returns:

  the human-readable name of this time zone in the default locale.

If this isn't sufficient, you can always try Joda Time.

Upvotes: 4

Thomas Lötzer
Thomas Lötzer

Reputation: 25411

If you're missing the offset, have a look at the getOffset()-method on TimeZone. That should give you enough information to calculate the offset from GMT.

Upvotes: 1

Related Questions