How can I format the default timezone as GMT [+/-]HH:MM?

Joe Sam Shirah

From the sample given at Using Predefined Formats in The Java Tutorial, one might think that getting a TimeInstance with a locale for Germany would do the trick. Unfortunately, this is not the case.

The GMT differential is only shown for time zones that have no established names. Because of this, the only method that occurs to me is to set all time zone names for the specific instance to "GMT". These strings are kept in a DateFormatSymbols object that belongs to the SimpleDateFormat returned when a TimeInstance is requested. Note that the docs say a SimpleDateFormat is "usually" returned, so this should be checked. This is really making a long story short, but here's code that does what you want:

import java.text.*;
import java.util.*;

public class GMTFmt

  public static void main( String[] args )

    DateFormat dfGMT = DateFormat.getTimeInstance(
      DateFormat.LONG );

    if( dfGMT instanceof SimpleDateFormat )
      DateFormatSymbols dfs =
      String[][] sZS = dfs.getZoneStrings();

      for( int i = 0; i < sZS.length; i++ )
        System.out.println( sZS[i][0] );
        sZS[i][0] = "GMT";


     System.out.println( dfGMT.format( new Date() ) );

  } // end main
}  // End class GMTFmt

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.