Get System time zone - Android java.util

Android examples for java.util:Locale

Description

Get System time zone

Demo Code

import java.util.Calendar;
import java.util.Locale;

import android.content.Context;
import android.content.res.Configuration;
import android.provider.Settings;

public class Main {
  private static final int DEFAULT_TIME_ZONE = 8;

  /**/*from   w w  w. j av  a2 s.  com*/
   * Get time zone
   *
   * @param context
   *          The context of the application.
   * @return The time zone, default 8
   */
  public static int getTimeZone(Context context) {
    try {
      Locale locale = getLocale(context);
      Calendar calendar = Calendar.getInstance(locale);
      if (calendar != null) {
        return calendar.getTimeZone().getRawOffset() / 3600000;
      }
    } catch (Exception e) {

    }

    return DEFAULT_TIME_ZONE;
  }

  /**
   * Get user config locale. Use default locale if failed.
   */
  private static Locale getLocale(Context context) {
    Locale locale = null;
    try {
      Configuration configuration = new Configuration();
      configuration.setToDefaults();
      Settings.System.getConfiguration(context.getContentResolver(), configuration);
      if (configuration != null) {
        locale = configuration.locale;
      }
    } catch (Exception e) {

    }

    if (locale == null) {
      locale = Locale.getDefault();
    }

    return locale;
  }
}

Related Tutorials