Example usage for java.util TimeZone getDisplayName

List of usage examples for java.util TimeZone getDisplayName

Introduction

In this page you can find the example usage for java.util TimeZone getDisplayName.

Prototype

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

Source Link

Document

Returns a name in the specified style of this TimeZone suitable for presentation to the user in the specified locale .

Usage

From source file:Main.java

public static void main(String args[]) {

    // create default time zone object
    TimeZone timezone = TimeZone.getTimeZone("US");

    // get display name for specific locale
    String disname = timezone.getDisplayName(true, 1, new Locale("EN", "US"));

    // checking display name         
    System.out.println("Display name is :" + disname);
}

From source file:Main.java

/**
 * Returns a formatted string representation of time in <code>milliseconds</code>
 * @param milliseconds Long value representing the time to be formatted
 * @return Formatted string representation of time in <code>milliseconds</code>
 *///from   w  w w.j  a v  a  2  s .  c o  m
public static String getOfxFormattedTime(long milliseconds) {
    Date date = new Date(milliseconds);
    String dateString = OFX_DATE_FORMATTER.format(date);
    TimeZone tz = Calendar.getInstance().getTimeZone();
    int offset = tz.getRawOffset();
    int hours = (int) ((offset / (1000 * 60 * 60)) % 24);
    String sign = offset > 0 ? "+" : "";
    return dateString + "[" + sign + hours + ":" + tz.getDisplayName(false, TimeZone.SHORT, Locale.getDefault())
            + "]";
}

From source file:com.lm.lic.manager.util.GenUtil.java

public static Date resetClientTimezone(HttpServletRequest request, Date date) {
    final TimeZone timeZone = TimeZone.getDefault();
    final boolean daylight = timeZone.inDaylightTime(date);
    final Locale locale = request.getLocale();
    String tzName = timeZone.getDisplayName(daylight, TimeZone.LONG, locale);
    // String countryCode = locale.getCountry();
    // TimeZone ltz = TimeZone.getTimeZone(countryCode);
    // TimeZoneNameUtility.getZoneStrings(locale);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);//from www .  ja v  a  2  s.co  m
    cal.setTimeZone(TimeZone.getTimeZone(tzName));
    return cal.getTime();
}

From source file:org.eclipse.gyrex.jobs.internal.commands.LsCmd.java

private void printSchedule(final ISchedule schedule) {
    final StrBuilder info = new StrBuilder();
    info.append(schedule.getId());/*from   ww  w . ja  va  2 s .c  o  m*/
    if (!schedule.isEnabled()) {
        info.appendln(" DISABLED");
    }

    final TimeZone timeZone = schedule.getTimeZone();
    info.append("  time zone: ").append(timeZone.getDisplayName(false, TimeZone.LONG, Locale.US))
            .appendln(timeZone.useDaylightTime() ? " (will adjust to daylight changes)"
                    : " (independent of daylight changes)");
    info.append("      queue: ").appendln(null != schedule.getQueueId() ? schedule.getQueueId() : "(default)");
    String prefix = "    entries: ";

    final List<IScheduleEntry> entries = schedule.getEntries();
    if (!entries.isEmpty()) {
        for (final IScheduleEntry entry : entries) {
            info.append(prefix).append(entry.getId()).append(' ').append(entry.getCronExpression()).append(' ')
                    .append(entry.getJobTypeId()).appendNewLine();
            prefix = "             ";
            final Map<String, String> parameter = entry.getJobParameter();
            if (!parameter.isEmpty()) {
                final Set<Entry<String, String>> entrySet = parameter.entrySet();
                for (final Entry<String, String> param : entrySet) {
                    info.append(prefix).append("    ").append(param.getKey()).append('=')
                            .appendln(param.getValue());
                }
            }
        }
    } else {
        info.append(prefix).appendln("(none)");
    }
    printf("%s", info.toString());
    return;
}

From source file:org.dpadgett.timer.WorldClockFragment.java

private void newClockDialog(final int position) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(context.getString(R.string.world_clock_select_timezone));
    final Map<String, String> timezoneNameToId = new HashMap<String, String>();
    final Set<Integer> timezones = new TreeSet<Integer>();
    final Map<Integer, List<String>> offsetToName = new HashMap<Integer, List<String>>();
    final long currentTime = System.currentTimeMillis();

    for (final String timezone : TimeZone.getAvailableIDs()) {
        final TimeZone tz = TimeZone.getTimeZone(timezone);
        final boolean isDaylight = tz.useDaylightTime();
        final String timezoneName = tz.getDisplayName(isDaylight, TimeZone.LONG, Locale.getDefault());
        if (timezoneNameToId.containsKey(timezoneName)) {
            continue;
        }/*from  w w w .  j a va2s.  co  m*/
        final int millisOffset = tz.getOffset(currentTime);
        timezones.add(millisOffset);
        if (!offsetToName.containsKey(millisOffset)) {
            offsetToName.put(millisOffset, new ArrayList<String>());
        }
        offsetToName.get(millisOffset).add(timezoneName);
        timezoneNameToId.put(timezoneName, timezone);
    }
    for (final List<String> names : offsetToName.values()) {
        Collections.sort(names);
    }
    if (position > -1) {
        builder.setPositiveButton(context.getString(R.string.world_clock_button_remove),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        clockList.remove(position);
                        clocksListAdapter.notifyDataSetChanged();

                        final SharedPreferences.Editor prefs = context
                                .getSharedPreferences("WorldClocks", Context.MODE_PRIVATE).edit();
                        prefs.putInt("numClocks", clockList.size());
                        int idx;
                        for (idx = position; idx < clockList.size(); idx++) {
                            prefs.putString("clock" + idx, clockList.get(idx));
                        }
                        prefs.remove("clock" + idx);
                        prefs.commit();
                    }
                });
    }
    final LinearLayout tzView = (LinearLayout) LayoutInflater.from(context)
            .inflate(R.layout.timezone_picker_dialog, (ViewGroup) finder.findViewById(R.id.layout_root));

    final List<String> initialItems = new ArrayList<String>();
    initialItems.add(context.getString(R.string.world_clock_timezone_gmt));
    initialItems.add(context.getString(R.string.world_clock_timezone_utc));
    final ArrayAdapter<String> adapter = ArrayAdapter.newArrayAdapter(context,
            R.layout.timezone_dialog_list_item, initialItems);
    final ListView timezoneList = (ListView) tzView.findViewById(R.id.timezoneList);
    timezoneList.setAdapter(adapter);

    final TextView sliderView = (TextView) tzView.findViewById(R.id.timezoneLabel);

    final SeekBar timezoneSeeker = (SeekBar) tzView.findViewById(R.id.timezoneSeeker);
    final List<Integer> timezonesList = new ArrayList<Integer>(timezones);
    timezoneSeeker.setMax(timezonesList.size() - 1);
    if (position > -1) {
        final int offset = TimeZone.getTimeZone(clockList.get(position)).getOffset(currentTime);
        timezoneSeeker.setProgress(timezonesList.indexOf(offset));
    } else {
        timezoneSeeker.setProgress(timezonesList.indexOf(0));
    }
    timezoneSeeker.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        // initialize the timezoneSeeker
        {
            onProgressChanged(timezoneSeeker, timezoneSeeker.getProgress(), false);
        }

        @Override
        public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {
            adapter.clear();
            adapter.addAll(offsetToName.get(timezonesList.get(progress)));
            final int millisOffset = timezonesList.get(progress);
            String offset = String.format("%02d:%02d", Math.abs(millisOffset / 1000 / 60 / 60),
                    Math.abs(millisOffset / 1000 / 60) % 60);
            if (millisOffset / 1000 / 60 / 60 < 0) {
                offset = "-" + offset;
            } else {
                offset = "+" + offset;
            }
            sliderView.setText(context.getString(R.string.world_clock_timezone_label) + offset);
        }

        @Override
        public void onStartTrackingTouch(final SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(final SeekBar seekBar) {
        }
    });
    builder.setView(tzView);
    final AlertDialog alert = builder.create();

    timezoneList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, final int selectedPosition,
                final long id) {
            final String timezoneName = adapter.getItem(selectedPosition);
            final String timezone = timezoneNameToId.get(timezoneName);
            addNewClock(timezone, position);
            alert.dismiss();
        }
    });

    alert.show();
}

From source file:com.application.utils.FastDatePrinter.java

/**
 * <p>Gets the time zone display name, using a cache for performance.</p>
 *
 * @param tz       the zone to query//  www . j  av a 2  s.c om
 * @param daylight true if daylight savings
 * @param style    the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT}
 * @param locale   the locale to use
 * @return the textual name of the time zone
 */
static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style,
        final Locale locale) {
    final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale);
    String value = cTimeZoneDisplayCache.get(key);
    if (value == null) {
        // This is a very slow call, so cache the results.
        value = tz.getDisplayName(daylight, style, locale);
        final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value);
        if (prior != null) {
            value = prior;
        }
    }
    return value;
}

From source file:DateFormatUtils.java

/**
 * <p>Gets the time zone display name, using a cache for performance.</p>
 * /*w  w  w  .  j  a va 2 s . co  m*/
 * @param tz  the zone to query
 * @param daylight  true if daylight savings
 * @param style  the style to use <code>TimeZone.LONG</code>
 *  or <code>TimeZone.SHORT</code>
 * @param locale  the locale to use
 * @return the textual name of the time zone
 */
static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
    Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
    String value = (String) cTimeZoneDisplayCache.get(key);
    if (value == null) {
        // This is a very slow call, so cache the results.
        value = tz.getDisplayName(daylight, style, locale);
        cTimeZoneDisplayCache.put(key, value);
    }
    return value;
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public String getServerTimezone(Locale locale) {
    TimeZone timeZone = TimeZone.getDefault();
    boolean daylight = timeZone.inDaylightTime(new Date());

    // Get the short timezone display name with respect to DST
    String timeZoneDisplay = timeZone.getDisplayName(daylight, TimeZone.SHORT, locale);

    // Get the offset in hours (divide by number of milliseconds in an hour)
    int offset = timeZone.getOffset(System.currentTimeMillis()) / (3600000);

    // Get the offset display in either UTC -x or UTC +x
    String offsetDisplay = (offset < 0) ? String.valueOf(offset) : "+" + offset;
    timeZoneDisplay += " (UTC " + offsetDisplay + ")";

    return timeZoneDisplay;
}

From source file:com.landenlabs.all_devtool.SystemFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*  w  w w .ja v a 2s .  co m*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        long heapSize = Debug.getNativeHeapSize();
        // long maxHeap = Runtime.getRuntime().maxMemory();

        // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo();
        int largHeapMb = actMgr.getLargeMemoryClass();
        int heapMb = actMgr.getMemoryClass();

        MemoryInfo memInfo = new MemoryInfo();
        actMgr.getMemoryInfo(memInfo);

        final String sFmtMB = "%.2f MB";
        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB));
        listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB));
        if (Build.VERSION.SDK_INT >= 16) {
            listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB));
        }
        listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB));
        listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb));
        listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb));
        addBuild("Memory...", listStr);
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState();
        int errCnt = (procErrList == null ? 0 : procErrList.size());
        procErrList = null;

        // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses();
        int procCnt = actMgr.getRunningAppProcesses().size();
        int srvCnt = actMgr.getRunningServices(100).size();

        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("#Processes", String.valueOf(procCnt));
        listStr.put("#Proc With Err", String.valueOf(errCnt));
        listStr.put("#Services", String.valueOf(srvCnt));
        // Requires special permission
        //   int taskCnt = actMgr.getRunningTasks(100).size();
        //   listStr.put("#Tasks",  String.valueOf(taskCnt));
        addBuild("Processes...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Processes %s", ex.getMessage());
    }

    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();
        listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity()));
        listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize()));
        putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness());
        putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey());
        addBuild("Misc...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Misc %s", ex.getMessage());
    }

    // --------------- Locale / Timezone -------------
    try {
        Locale ourLocale = Locale.getDefault();
        Date m_date = new Date();
        TimeZone tz = TimeZone.getDefault();

        Map<String, String> localeListStr = new LinkedHashMap<String, String>();

        localeListStr.put("Locale Name", ourLocale.getDisplayName());
        localeListStr.put(" Variant", ourLocale.getVariant());
        localeListStr.put(" Country", ourLocale.getCountry());
        localeListStr.put(" Country ISO", ourLocale.getISO3Country());
        localeListStr.put(" Language", ourLocale.getLanguage());
        localeListStr.put(" Language ISO", ourLocale.getISO3Language());
        localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage());

        localeListStr.put("TimeZoneID", tz.getID());
        localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No");
        localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No");
        localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale));
        localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale));

        addBuild("Locale TZ...", localeListStr);
    } catch (Exception ex) {
        m_log.e("Locale/TZ %s", ex.getMessage());
    }

    // --------------- Location Services -------------
    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();

        final LocationManager locMgr = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        GpsStatus gpsStatus = locMgr.getGpsStatus(null);
        if (gpsStatus != null) {
            listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix()));

            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            while (sat.hasNext()) {
                GpsSatellite satellite = sat.next();

                putIf(listStr,
                        String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()),
                        String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix());
            }
        }

        Location location = null;
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }

        if (null != location) {
            listStr.put(location.getProvider() + " lat,lng",
                    String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude()));
        }
        if (listStr.size() != 0) {
            List<String> gpsProviders = locMgr.getAllProviders();
            int idx = 1;
            for (String providerName : gpsProviders) {
                LocationProvider provider = locMgr.getProvider(providerName);
                if (null != provider) {
                    listStr.put(providerName,
                            (locMgr.isProviderEnabled(providerName) ? "On " : "Off ")
                                    + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(),
                                            provider.getPowerRequirement()));
                }
            }
            addBuild("GPS...", listStr);
        } else
            addBuild("GPS", "Off");
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Application Info -------------
    ApplicationInfo appInfo = getActivity().getApplicationInfo();
    if (null != appInfo) {
        Map<String, String> appList = new LinkedHashMap<String, String>();
        try {
            appList.put("ProcName", appInfo.processName);
            appList.put("PkgName", appInfo.packageName);
            appList.put("DataDir", appInfo.dataDir);
            appList.put("SrcDir", appInfo.sourceDir);
            //    appList.put("PkgResDir", getActivity().getPackageResourcePath());
            //     appList.put("PkgCodeDir", getActivity().getPackageCodePath());
            String[] dbList = getActivity().databaseList();
            if (dbList != null && dbList.length != 0)
                appList.put("DataBase", dbList[0]);
            // getActivity().getComponentName().

        } catch (Exception ex) {
        }
        addBuild("AppInfo...", appList);
    }

    // --------------- Account Services -------------
    final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
    if (null != accMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        try {
            for (Account account : accMgr.getAccounts()) {
                strList.put(account.name, account.type);
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Accounts...", strList);
    }

    // --------------- Package Features -------------
    PackageManager pm = getActivity().getPackageManager();
    FeatureInfo[] features = pm.getSystemAvailableFeatures();
    if (features != null) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        for (FeatureInfo featureInfo : features) {
            strList.put(featureInfo.name, "");
        }
        addBuild("Features...", strList);
    }

    // --------------- Sensor Services -------------
    final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (null != senMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL);
        try {
            for (Sensor sensor : listSensor) {
                strList.put(sensor.getName(), sensor.getVendor());
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Sensors...", strList);
    }

    try {
        if (Build.VERSION.SDK_INT >= 17) {
            final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
            if (null != userMgr) {
                try {
                    addBuild("UserName", userMgr.getUserName());
                } catch (Exception ex) {
                    m_log.e(ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
    }

    try {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.SCREEN_OFF_TIMEOUT);
        strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000));
        int rotate = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION);
        strList.put("RotateEnabled", String.valueOf(rotate));
        if (Build.VERSION.SDK_INT >= 17) {
            // Global added in API 17
            int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED);
            strList.put("AdbEnabled", String.valueOf(adb));
        }
        addBuild("Settings...", strList);
    } catch (Exception ex) {
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}