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 final String getDisplayName() 

Source Link

Document

Returns a long standard time name of this TimeZone suitable for presentation to the user in the default locale.

Usage

From source file:com.microsoft.exchange.DateHelpTest.java

@Test
public void systemTimeZone() {
    List<String> availableIDs = Arrays.asList(TimeZone.getAvailableIDs());
    assertFalse(CollectionUtils.isEmpty(availableIDs));
    assertTrue(availableIDs.contains(TimeZones.UTC_ID));
    assertTrue(availableIDs.contains("UTC"));

    TimeZone ical4jUTC = TimeZone.getTimeZone(TimeZones.UTC_ID);
    TimeZone sysUTC = TimeZone.getTimeZone("UTC");

    assertEquals(ical4jUTC.getDSTSavings(), sysUTC.getDSTSavings());
    assertEquals(ical4jUTC.getRawOffset(), sysUTC.getRawOffset());
    assertTrue(ical4jUTC.hasSameRules(sysUTC));

    TimeZone origDefaultTimeZone = TimeZone.getDefault();
    assertNotNull(origDefaultTimeZone);/*from w  w  w.j  a  va  2  s  . c  o  m*/
    assertEquals(TimeZone.getDefault().getRawOffset(), origDefaultTimeZone.getRawOffset());

    log.info("TimeZone.DisplayName=" + origDefaultTimeZone.getDisplayName());
    log.info("TimeZone.ID=" + origDefaultTimeZone.getID());
    log.info("TimeZone.DSTSavings=" + origDefaultTimeZone.getDSTSavings());
    log.info("TimeZone.RawOffset=" + origDefaultTimeZone.getRawOffset());
    log.info("TimeZone.useDaylightTime=" + origDefaultTimeZone.useDaylightTime());

    TimeZone.setDefault(ical4jUTC);
    assertEquals(ical4jUTC, TimeZone.getDefault());
    log.info(" -- Defualt Time Zone has been changed successfully! -- ");

    TimeZone newDefaultTimeZone = TimeZone.getDefault();
    log.info("TimeZone.DisplayName=" + newDefaultTimeZone.getDisplayName());
    log.info("TimeZone.ID=" + newDefaultTimeZone.getID());
    log.info("TimeZone.DSTSavings=" + newDefaultTimeZone.getDSTSavings());
    log.info("TimeZone.RawOffset=" + newDefaultTimeZone.getRawOffset());
    log.info("TimeZone.useDaylightTime=" + newDefaultTimeZone.useDaylightTime());
}

From source file:org.adempiere.webui.dashboard.CalendarWindow.java

private void setTimeZone() {
    String alternateTimeZone = MSysConfig.getValue(MSysConfig.CALENDAR_ALTERNATE_TIMEZONE, "Pacific Time=PST",
            Env.getAD_Client_ID(Env.getCtx()));
    TimeZone defaultTimeZone = TimeZone.getDefault();
    calendars.addTimeZone(defaultTimeZone.getDisplayName(), defaultTimeZone);
    if (!Util.isEmpty(alternateTimeZone, true)) {
        if (!alternateTimeZone.equalsIgnoreCase(defaultTimeZone.getDisplayName())) {
            String[] pair = alternateTimeZone.split("=");
            calendars.addTimeZone(pair[0].trim(), pair[1].trim());
        }/*from www. j  a  va 2 s.  c om*/
    }
}

From source file:RhodesService.java

public static String getTimezoneStr() {
    Calendar cal = Calendar.getInstance();
    TimeZone tz = cal.getTimeZone();
    return tz.getDisplayName();
}

From source file:com.blackducksoftware.tools.ccimporter.config.CCIConfigurationManager.java

/**
 * Make sure timezone is set to a valid timezone ID string
 *//*from  w ww  . j  a v  a  2 s .  c om*/
private void ensureTimeZoneIsSet() {
    // TODO: Temporary workaround to provide timezones. This
    // handles the case whereby
    // utility is run against a server that is not in the same
    // time zone.
    TimeZone tz;
    String userSpecifiedTimeZone = timeZone;

    if (userSpecifiedTimeZone != null && !userSpecifiedTimeZone.isEmpty()) {
        tz = TimeZone.getTimeZone(userSpecifiedTimeZone);
        log.info("User specified time zone recognized, using: " + tz.getDisplayName());
    } else {
        tz = TimeZone.getDefault();
    }

    setTimeZone(tz.getID());
}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

/**
 * //from   ww  w .j a v  a  2s .c o m
 * Map returned:
 * 
 * <pre>
 *   TZ = Timezone
 *     id = Timezone ID
 *     display = Timezone display name
 *     offset = Offset from UTC (in ms)
 *   SDK = SDK Version
 *   download = default download path
 *   appcache = Location of application cache 
 *   sdcard = Space on sdcard
 *     availblocks = Available blocks
 *     blockcount = Total Blocks
 *     blocksize = size of block.
 * </pre>
 */
@Rpc(description = "A map of various useful environment details")
public Map<String, Object> environment() {
    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, Object> zone = new HashMap<String, Object>();
    Map<String, Object> space = new HashMap<String, Object>();
    TimeZone tz = TimeZone.getDefault();
    zone.put("id", tz.getID());
    zone.put("display", tz.getDisplayName());
    zone.put("offset", tz.getOffset((new Date()).getTime()));
    result.put("TZ", zone);
    result.put("SDK", android.os.Build.VERSION.SDK);
    result.put("download", FileUtils.getExternalDownload().getAbsolutePath());
    result.put("appcache", mService.getCacheDir().getAbsolutePath());
    try {
        StatFs fs = new StatFs("/sdcard");
        space.put("availblocks", fs.getAvailableBlocks());
        space.put("blocksize", fs.getBlockSize());
        space.put("blockcount", fs.getBlockCount());
    } catch (Exception e) {
        space.put("exception", e.toString());
    }
    result.put("sdcard", space);
    return result;
}

From source file:com.rareventure.gps2.reviewer.map.MediaGalleryFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (gtum == null)
        return null;

    View v = inflater.inflate(R.layout.media_gallery, container, false);

    View glassPane = (View) v.findViewById(R.id.glass_pane);

    glassPane.setOnClickListener(new OnClickListener() {

        @Override/*from   ww w. j  a va  2  s  . c o  m*/
        public void onClick(View v) {
            finishBrowsing();
        }
    });

    // Reference the Gallery view
    gallery = (Gallery) v.findViewById(R.id.gallery);

    //remove the alphaness
    gallery.setUnselectedAlpha(1.0f);

    gallery.setSpacing((int) Util.convertDpToPixel(10, this.getActivity()));

    // Set a item click listener, and just Toast the clicked position
    gallery.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id) {
            MediaLocTime mlt = mlts.get((int) id);

            if (!mlt.isClean(gtum))
                return;

            ViewImage.mAllImages = mlts;
            ViewImage.mCurrentPosition = (int) id;

            Intent intent = new Intent(getActivity(), ViewImage.class);
            gtum.startInternalActivity(intent);
            //               FullMediaGalleryActivity.setFullMediaGalleryActivityData(mlts, (int)id);
            //               startActivity(new Intent(getActivity(), FullMediaGalleryActivity.class));
            //               
            //               if(mlt.getType() == MediaLocTime.TYPE_IMAGE)
            //                  Util.viewMediaInGallery(gtum, mlt.getFilename(), true);
            //               else
            //                  Util.viewMediaInGallery(gtum, mlt.getFilename(), false //video
            //                        );
        }
    });

    final TextView index = (TextView) v.findViewById(R.id.index);
    final TextView timeAndTimezone = (TextView) v.findViewById(R.id.time_and_timezone);

    final String indexTextFormat = getResources().getText(R.string.x_of_x_items_format).toString();
    final String nothingTextFormat = getResources().getText(R.string.x_items_format).toString();
    final String timeWithTimezoneFormat = getResources()
            .getText(R.string.media_gallery_strip_time_with_timezone).toString();

    final SimpleDateFormat timeAndDateSdf = new SimpleDateFormat(getString(R.string.time_and_date_format));

    gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            int secs = mlts.get(position).getTimeSecs();

            /* ttt_installer:remove_line */Log.d(GTG.TAG, "Mlt selected: " + mlts.get(position));

            TimeZone tz = GTG.tztSet.getTimeZoneTimeOrNullIfUnknwonOrLocalTime(secs);

            if (tz != null)
                timeAndDateSdf.setTimeZone(tz);
            else
                timeAndDateSdf.setTimeZone(Util.getCurrTimeZone());

            String dateStr = timeAndDateSdf.format(new Date(secs * 1000l));

            index.setText(String.format(indexTextFormat, (position + 1), mlts.size()));

            if (tz != null)
                timeAndTimezone.setText(String.format(timeWithTimezoneFormat, dateStr, tz.getDisplayName()));
            else
                timeAndTimezone.setText(dateStr);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            index.setText(String.format(nothingTextFormat, mlts.size()));

            timeAndTimezone.setText("");

        }
    });
    ;
    ((Gallery) v.findViewById(R.id.gallery))
            .setAdapter(adapter = new MltAdapter(getActivity(), inflater, mlts));

    // Inflate the layout for this fragment
    return v;
}

From source file:org.sakaiproject.tool.summarycalendar.ui.CalendarBean.java

/**
 * Get the TimeZone for the current user
 * @return//from ww  w  . ja v  a2 s. co m
 */
private TimeZone getCurrentUserTimezone() {

    TimeZone tz = TimeService.getLocalTimeZone();
    LOG.debug("got tz " + tz.getDisplayName());
    return tz;
}

From source file:com.trial.phonegap.plugin.calendar.CalendarAccessorGoogle.java

/**
 * Transforms a JSONObject object with information about an event in an event object
 * @param JsonEvent an JSONObject object with data about an event
 * @return an event object with te information within JSONObject object given by parameter
 * @throws JSONException/*from  w w w  .ja  v a2s  .c  o  m*/
 */
private Event jsonEventToEvent(JSONObject jsonEvent) throws JSONException {

    Event event = new Event();

    if (!jsonEvent.isNull("id")) {
        event.setId(jsonEvent.getString("id"));
    }

    if (!jsonEvent.isNull("recurrence")) {
        Recurrence recurrence = new Recurrence();
        recurrence.setRule(parseJsonRecurrenceRule(jsonEvent.getJSONObject("recurrence")));
        if (!(jsonEvent.isNull("start")) && (!jsonEvent.isNull("end"))) {
            Dt dt = new Dt();
            dt.setDate(DateUtils.stringCalendarDateToDateLocale(jsonEvent.getString("start"),
                    "yyyy-MM-dd HH:mm:ss"));

            TimeZone tm = TimeZone.getDefault();
            tm.setID(Locale.getDefault().getISO3Country());

            dt.setTimeZone(tm.getDisplayName());
            recurrence.setDtStart(dt);
            dt.setDate(DateUtils.stringCalendarDateToDateLocale(jsonEvent.getString("end"),
                    "yyyy-MM-dd HH:mm:ss"));
            recurrence.setDtEnd(dt);
        }
        event.setRecurrence(recurrence);
    }

    if (!jsonEvent.isNull("description")) {
        event.setTitle(jsonEvent.getString("description"));
    }

    if (!jsonEvent.isNull("location")) {
        List<Where> whereList = new ArrayList<Where>();
        Where where = new Where();
        where.description = jsonEvent.getString("location");
        whereList.add(where);

        event.setWhere(whereList);
    }

    if (jsonEvent.isNull("summary"))
        event.setSummary(jsonEvent.getString("summary"));
    if (jsonEvent.isNull("status"))
        event.setEventStatus(constantSelector(jsonEvent.getString("status")));
    if (jsonEvent.isNull("transparency"))
        event.setTransparency(constantSelector(jsonEvent.getString("transparency")));

    if (jsonEvent.isNull("recurrence")) {
        List<When> whenList = new ArrayList<When>();
        When when = new When();
        if (!jsonEvent.isNull("start"))
            when.startTime = new DateTime(DateUtils.stringCalendarDateToDateLocale(jsonEvent.getString("start"),
                    "yyyy-MM-dd HH:mm:ss"));
        if (!jsonEvent.isNull("end"))
            when.endTime = new DateTime(DateUtils.stringCalendarDateToDateLocale(jsonEvent.getString("end"),
                    "yyyy-MM-dd HH:mm:ss"));
        if (!jsonEvent.isNull("reminder"))
            when.reminders = parseJsonReminder(jsonEvent.getString("reminder"));
        whenList.add(when);
        event.setWhen(whenList);
    }

    return event;

}

From source file:org.openmeetings.app.remote.ConferenceService.java

public Map<String, Object> getAppointMentAndTimeZones(Long room_id) {
    try {//from w  ww. ja  v  a 2 s. c  o  m
        log.debug("getAppointMentDataForRoom");

        IConnection current = Red5.getConnectionLocal();
        String streamid = current.getClient().getId();

        log.debug("getCurrentRoomClient -2- " + streamid);

        RoomClient currentClient = this.clientListManager.getClientByStreamId(streamid);

        Rooms room = roommanagement.getRoomById(room_id);

        if (room.getAppointment() == false) {
            throw new IllegalStateException("Room has no appointment");
        }

        Appointment appointment = appointmentLogic.getAppointmentByRoom(room_id);

        Map<String, Object> returnMap = new HashMap<String, Object>();

        returnMap.put("appointment", appointment);

        Users us = userManagement.getUserById(currentClient.getUser_id());
        TimeZone timezone = timezoneUtil.getTimezoneByUser(us);

        returnMap.put("appointment", appointment);

        returnMap.put("start",
                CalendarPatterns.getDateWithTimeByMiliSeconds(appointment.getAppointmentStarttime(), timezone));
        returnMap.put("end",
                CalendarPatterns.getDateWithTimeByMiliSeconds(appointment.getAppointmentEndtime(), timezone));
        returnMap.put("timeZone", timezone.getDisplayName());

        return returnMap;
    } catch (Exception e) {
        log.error("getAppointMentAndTimeZones ", e);
        return null;
    }

}

From source file:org.apache.oozie.command.coord.CoordMaterializeTransitionXCommand.java

/**
 * Create action instances starting from "startMatdTime" to "endMatdTime" and store them into coord action table.
 *
 * @param dryrun if this is a dry run//from  ww  w. j  av a  2s  .  c om
 * @throws Exception thrown if failed to materialize actions
 */
protected String materializeActions(boolean dryrun) throws Exception {

    Configuration jobConf = null;
    try {
        jobConf = new XConfiguration(new StringReader(coordJob.getConf()));
    } catch (IOException ioe) {
        LOG.warn("Configuration parse error. read from DB :" + coordJob.getConf(), ioe);
        throw new CommandException(ErrorCode.E1005, ioe.getMessage(), ioe);
    }

    String jobXml = coordJob.getJobXml();
    Element eJob = XmlUtils.parseXml(jobXml);
    TimeZone appTz = DateUtils.getTimeZone(coordJob.getTimeZone());

    String frequency = coordJob.getFrequency();
    TimeUnit freqTU = TimeUnit.valueOf(coordJob.getTimeUnitStr());
    TimeUnit endOfFlag = TimeUnit.valueOf(eJob.getAttributeValue("end_of_duration"));
    Calendar start = Calendar.getInstance(appTz);
    start.setTime(startMatdTime);
    DateUtils.moveToEnd(start, endOfFlag);
    Calendar end = Calendar.getInstance(appTz);
    end.setTime(endMatdTime);
    lastActionNumber = coordJob.getLastActionNumber();
    //Intentionally printing dates in their own timezone, not Oozie timezone
    LOG.info("materialize actions for tz=" + appTz.getDisplayName() + ",\n start=" + start.getTime() + ", end="
            + end.getTime() + ",\n timeUnit " + freqTU.getCalendarUnit() + ",\n frequency :" + frequency + ":"
            + freqTU + ",\n lastActionNumber " + lastActionNumber);
    // Keep the actual start time
    Calendar origStart = Calendar.getInstance(appTz);
    origStart.setTime(coordJob.getStartTimestamp());
    // Move to the End of duration, if needed.
    DateUtils.moveToEnd(origStart, endOfFlag);

    StringBuilder actionStrings = new StringBuilder();
    Date jobPauseTime = coordJob.getPauseTime();
    Calendar pause = null;
    if (jobPauseTime != null) {
        pause = Calendar.getInstance(appTz);
        pause.setTime(DateUtils.convertDateToTimestamp(jobPauseTime));
    }

    String action = null;
    int numWaitingActions = dryrun ? 0
            : jpaService.execute(new CoordActionsActiveCountJPAExecutor(coordJob.getId()));
    int maxActionToBeCreated = coordJob.getMatThrottling() - numWaitingActions;
    // If LAST_ONLY and all materialization is in the past, ignore maxActionsToBeCreated
    boolean ignoreMaxActions = (coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.LAST_ONLY)
            || coordJob.getExecutionOrder().equals(CoordinatorJob.Execution.NONE))
            && endMatdTime.before(new Date());
    LOG.debug("Coordinator job :" + coordJob.getId() + ", maxActionToBeCreated :" + maxActionToBeCreated
            + ", Mat_Throttle :" + coordJob.getMatThrottling() + ", numWaitingActions :" + numWaitingActions);

    boolean isCronFrequency = false;

    Calendar effStart = (Calendar) start.clone();
    try {
        int intFrequency = Integer.parseInt(coordJob.getFrequency());
        effStart = (Calendar) origStart.clone();
        effStart.add(freqTU.getCalendarUnit(), lastActionNumber * intFrequency);
    } catch (NumberFormatException e) {
        isCronFrequency = true;
    }

    boolean firstMater = true;
    while (effStart.compareTo(end) < 0 && (ignoreMaxActions || maxActionToBeCreated-- > 0)) {
        if (pause != null && effStart.compareTo(pause) >= 0) {
            break;
        }

        Date nextTime = effStart.getTime();

        if (isCronFrequency) {
            if (effStart.getTime().compareTo(startMatdTime) == 0 && firstMater) {
                effStart.add(Calendar.MINUTE, -1);
                firstMater = false;
            }

            nextTime = CoordCommandUtils.getNextValidActionTimeForCronFrequency(effStart.getTime(), coordJob);
            effStart.setTime(nextTime);
        }

        if (effStart.compareTo(end) < 0) {

            if (pause != null && effStart.compareTo(pause) >= 0) {
                break;
            }
            CoordinatorActionBean actionBean = new CoordinatorActionBean();
            lastActionNumber++;

            int timeout = coordJob.getTimeout();
            LOG.debug("Materializing action for time=" + DateUtils.formatDateOozieTZ(effStart.getTime())
                    + ", lastactionnumber=" + lastActionNumber + " timeout=" + timeout + " minutes");
            Date actualTime = new Date();
            action = CoordCommandUtils.materializeOneInstance(jobId, dryrun, (Element) eJob.clone(), nextTime,
                    actualTime, lastActionNumber, jobConf, actionBean);
            actionBean.setTimeOut(timeout);
            if (!dryrun) {
                storeToDB(actionBean, action, jobConf); // Storing to table

            } else {
                actionStrings.append("action for new instance");
                actionStrings.append(action);
            }
        } else {
            break;
        }

        if (!isCronFrequency) {
            effStart = (Calendar) origStart.clone();
            effStart.add(freqTU.getCalendarUnit(),
                    lastActionNumber * Integer.parseInt(coordJob.getFrequency()));
        }
    }

    if (isCronFrequency) {
        if (effStart.compareTo(end) < 0 && !(ignoreMaxActions || maxActionToBeCreated-- > 0)) {
            //Since we exceed the throttle, we need to move the nextMadtime forward
            //to avoid creating duplicate actions
            if (!firstMater) {
                effStart.setTime(
                        CoordCommandUtils.getNextValidActionTimeForCronFrequency(effStart.getTime(), coordJob));
            }
        }
    }

    endMatdTime = effStart.getTime();

    if (!dryrun) {
        return action;
    } else {
        return actionStrings.toString();
    }
}