Example usage for java.util TimeZone getOffset

List of usage examples for java.util TimeZone getOffset

Introduction

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

Prototype

public int getOffset(long date) 

Source Link

Document

Returns the offset of this time zone from UTC at the specified date.

Usage

From source file:org.kalypso.core.KalypsoCorePlugin.java

/**
 * Gets the kalypso timezone (to be used to display any dates in the UI).<br>
 * The timezone is set in the user-preferences. If the preference is not set, the value of the system property
 * 'kalypso.timezone' will be used, or, if not set, the system timezone (see {@link TimeZone#getDefault()}). <br>
 * The user preferences can explicitly be set to:
 * <ul>//w ww  .  ja va2  s  .  c o  m
 * <li>OS_TIMEZONE: {@link TimeZone#getDefault() is always used}</li>
 * <li>CONFIG_TIMEZONE: timezone definition from config.ini (kalypso.timezone) is used (defaults to system timezone if not set)</li>
 * </ul>
 */
public TimeZone getTimeZone() {
    final TimeZone timezone = getInternalTimeZone();

    /** we want to get rid of daylight saving times and only support GMT based time zones! */
    final String identifier = timezone.getID();
    if (!StringUtils.containsIgnoreCase(identifier, "gmt")) //$NON-NLS-1$
    {
        final Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, 0); // get offset from winter daylight saving time!
        final int offset = timezone.getOffset(calendar.getTimeInMillis());

        return TimeZone.getTimeZone(String.format("GMT%+d", offset)); //$NON-NLS-1$
    }

    return timezone;

}

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;
        }//w w  w.j a v  a 2 s  . c om
        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:org.exoplatform.webservice.cs.calendar.CalendarWebservice.java

private SingleEvent makeSingleEvent(CalendarSetting calSetting, CalendarEvent cEvent) {
    if (calSetting == null || cEvent == null) {
        throw new IllegalArgumentException("parameters must be not null");
    }//from w  w  w .  j  a va  2 s  .  co m
    SingleEvent event = new SingleEvent();
    event.setDescription(cEvent.getDescription());
    event.setEventState(cEvent.getEventState());
    event.setLocation(cEvent.getLocation());
    event.setPriority(cEvent.getPriority());
    event.setSummary(cEvent.getSummary());
    // evaluate timeoffset
    TimeZone timeZone = TimeZone.getTimeZone(calSetting.getTimeZone());
    event.setStartDateTime(cEvent.getFromDateTime().getTime());
    event.setStartTimeOffset(timeZone.getOffset(cEvent.getFromDateTime().getTime()));
    event.setEndDateTime(cEvent.getToDateTime().getTime());
    event.setEndTimeOffset(timeZone.getOffset(cEvent.getToDateTime().getTime()));
    return event;
}

From source file:CB_Core.Api.GroundspeakAPI.java

private static String GetUTCDate(Date date) {
    long utc = date.getTime();
    // date.getTime already returns utc timestamp. Conversion to utc is not necessary!!!
    // TimeZone tz = TimeZone.getDefault();
    TimeZone tzp = TimeZone.getTimeZone("GMT-8");
    // int offset = tz.getOffset(utc);
    utc += /* offset */-tzp.getOffset(utc);
    return "\\/Date(" + utc + ")\\/";
}

From source file:org.jasig.schedassist.model.DefaultEventUtilsImpl.java

@Override
public PeriodList calculateRecurrence(VEvent event, Date startBoundary, Date endBoundary) {
    Period period = new Period(new DateTime(startBoundary), new DateTime(endBoundary));
    PeriodList periodList = event.calculateRecurrenceSet(period);
    PeriodList results = new PeriodList();
    for (Object o : periodList) {
        Period p = (Period) o;

        if (isAllDayPeriod(p)) {
            // this period is broken
            // the Periods returned by ical4j's calculateRecurrenceSet have range start/ends that are off by the system default's timezone offset
            TimeZone systemTimezone = java.util.TimeZone.getDefault();

            int offset = systemTimezone.getOffset(p.getStart().getTime());
            Period fixed = new Period(new DateTime(DateUtils.addMilliseconds(p.getRangeStart(), -offset)),
                    new DateTime(DateUtils.addMilliseconds(p.getRangeEnd(), -offset)));
            results.add(fixed);/* w  ww.  j  a  va  2s . com*/
        } else {
            results.add(p);
        }
    }
    return results;
}

From source file:org.mycontroller.standalone.mysensors.ProcessRawMessage.java

private void internalSubMessageTypeSelector(RawMessage rawMessage) {
    //Log message data
    SensorLogUtils.setSensorInternalData(MESSAGE_TYPE_INTERNAL.get(rawMessage.getSubType()), rawMessage, null);
    _logger.debug("Message Type:{}", MESSAGE_TYPE_INTERNAL.get(rawMessage.getSubType()).toString());
    switch (MESSAGE_TYPE_INTERNAL.get(rawMessage.getSubType())) {
    case I_BATTERY_LEVEL:
        if (rawMessage.isTxMessage()) {
            return;
        }/* ww w  .j a v  a2s  .c o m*/
        _logger.debug("Battery Level:[nodeId:{},Level:{}%]", rawMessage.getNodeId(), rawMessage.getPayload());
        Node node = DaoUtils.getNodeDao().get(rawMessage.getNodeId());
        if (node == null) {
            updateNode(rawMessage);
            node = DaoUtils.getNodeDao().get(rawMessage.getNodeId());
        }
        node.setBatteryLevel(rawMessage.getPayload());
        DaoUtils.getNodeDao().update(node);
        //Update battery level in to metrics table
        MetricsBatteryUsage batteryUsage = new MetricsBatteryUsage(node, System.currentTimeMillis(),
                rawMessage.getPayloadDouble());
        DaoUtils.getMetricsBatteryUsageDao().create(batteryUsage);

        break;
    case I_TIME:
        if (rawMessage.isTxMessage()) {
            return;
        }
        TimeZone timeZone = TimeZone.getDefault();
        long utcTime = System.currentTimeMillis();
        long timeOffset = timeZone.getOffset(utcTime);
        long localTime = utcTime + timeOffset;
        rawMessage.setPayload(String.valueOf(localTime / 1000));
        rawMessage.setTxMessage(true);
        _logger.debug("Time Message:[{}]", rawMessage);
        ObjectFactory.getRawMessageQueue().putMessage(rawMessage);
        _logger.debug("Time request resolved.");
        break;
    case I_VERSION:
        _logger.debug("Gateway version requested by {}! Message:{}", AppProperties.APPLICATION_NAME,
                rawMessage);
        break;
    case I_ID_REQUEST:
        try {
            int nodeId = ObjectFactory.getAppProperties().getNextNodeId();
            rawMessage.setPayload(nodeId);
            rawMessage.setSubType(MESSAGE_TYPE_INTERNAL.I_ID_RESPONSE.ordinal());
            rawMessage.setTxMessage(true);
            ObjectFactory.getRawMessageQueue().putMessage(rawMessage);
            _logger.debug("New Id[{}] sent to node", nodeId);
        } catch (NodeIdException ex) {
            _logger.error("Unable to generate new node Id,", ex);
            SensorLogUtils.setSensorInternalData(MESSAGE_TYPE_INTERNAL.get(rawMessage.getSubType()), rawMessage,
                    ex.getMessage());
        }
        break;
    case I_INCLUSION_MODE:
        _logger.warn("Inclusion mode not supported by this controller! Message:{}", rawMessage);
        break;
    case I_CONFIG:
        if (rawMessage.isTxMessage()) {
            return;
        }
        rawMessage.setPayload(ObjectFactory.getAppProperties().getMetricType());
        rawMessage.setTxMessage(true);
        ObjectFactory.getRawMessageQueue().putMessage(rawMessage);
        _logger.debug("Configuration sent as follow[M/I]?:{}", rawMessage.getPayload());
        break;
    case I_LOG_MESSAGE:
        if (rawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Node trace-log message[nodeId:{},sensorId:{},message:{}]", rawMessage.getNodeId(),
                rawMessage.getChildSensorId(), rawMessage.getPayload());
        break;
    case I_SKETCH_NAME:
        if (rawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Internal Message[type:{},name:{}]", MESSAGE_TYPE_INTERNAL.get(rawMessage.getSubType()),
                rawMessage.getPayload());
        node = DaoUtils.getNodeDao().get(rawMessage.getNodeId());
        if (node == null) {
            DaoUtils.getNodeDao().create(new Node(rawMessage.getNodeId(), rawMessage.getPayload()));
        } else {
            node.setName(rawMessage.getPayload());
            DaoUtils.getNodeDao().update(node);
        }

        break;
    case I_SKETCH_VERSION:
        if (rawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Internal Message[type:{},version:{}]",
                MESSAGE_TYPE_INTERNAL.get(rawMessage.getSubType()), rawMessage.getPayload());
        node = DaoUtils.getNodeDao().get(rawMessage.getNodeId());
        node.setVersion(rawMessage.getPayload());
        DaoUtils.getNodeDao().createOrUpdate(node);
        break;

    case I_REBOOT:
        break;
    case I_GATEWAY_READY:
        if (rawMessage.isTxMessage()) {
            return;
        }
        _logger.debug("Gateway Ready[nodeId:{},message:{}]", rawMessage.getNodeId(), rawMessage.getPayload());
        break;

    case I_ID_RESPONSE:
        _logger.debug("Internal Message, Type:I_ID_RESPONSE[{}]", rawMessage);
        return;

    default:
        _logger.warn(
                "Internal Message[type:{},payload:{}], This type may not be supported (or) not implemented yet",
                MESSAGE_TYPE_INTERNAL.get(rawMessage.getSubType()), rawMessage.getPayload());
        break;
    }
}

From source file:org.apache.oozie.coord.CoordELFunctions.java

/**
 * Calculate the difference of timezone offset in minutes between dataset and coordinator job. <p> Depends on: <p>
 * 1. Timezone of both dataset and job <p> 2. Action creation Time
 *
 * @return difference in minutes (DataSet TZ Offset - Application TZ offset)
 */// w  ww . jav  a2s  .c  o m
public static int ph2_coord_tzOffset() {
    long actionCreationTime = getActionCreationtime().getTime();
    TimeZone dsTZ = ParamChecker.notNull(getDatasetTZ(), "DatasetTZ");
    TimeZone jobTZ = ParamChecker.notNull(getJobTZ(), "JobTZ");
    return (dsTZ.getOffset(actionCreationTime) - jobTZ.getOffset(actionCreationTime)) / (1000 * 60);
}

From source file:org.nodatime.tzvalidate.Java7Dump.java

@Override
public ZoneTransitions getTransitions(String id, int fromYear, int toYear) {
    TimeZone zone = TimeZone.getTimeZone(id);
    DateFormat nameFormat = new SimpleDateFormat("zzz", Locale.US);
    nameFormat.setTimeZone(zone);/*from w ww  . j ava 2 s  . co  m*/

    // Given the way we find transitions, we really don't want to go
    // from any earlier than this...
    if (fromYear < 1800) {
        fromYear = 1800;
    }

    Calendar calendar = GregorianCalendar.getInstance(UTC);
    calendar.set(fromYear, 0, 1, 0, 0, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    long start = calendar.getTimeInMillis();
    calendar.set(toYear, 0, 1, 0, 0, 0);
    long end = calendar.getTimeInMillis();
    Date date = new Date(start);

    ZoneTransitions transitions = new ZoneTransitions(id);
    transitions.addTransition(null, zone.getOffset(start), zone.inDaylightTime(date), nameFormat.format(date));

    Long transition = getNextTransition(zone, start - 1, end);
    while (transition != null) {
        date.setTime(transition);
        transitions.addTransition(date, zone.getOffset(transition), zone.inDaylightTime(date),
                nameFormat.format(date));
        transition = getNextTransition(zone, transition, end);
    }
    return transitions;
}

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

/**
 * /*  w w w.j ava2 s  . com*/
 * 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:org.exoplatform.calendar.service.impl.CalendarSearchServiceConnector.java

private SearchResult buildResult(SearchContext sc, Collection<String> siteKeys, String dataType, Object iter,
        CalendarSetting calSeting) {//  w  w  w .ja v  a 2s.  c o  m
    try {
        String calId = null;
        if (iter instanceof Row) {
            Row row = (Row) iter;
            calId = row.getValue(Utils.EXO_CALENDAR_ID).getString();
        } else {
            Node eventNode = (Node) iter;
            if (eventNode.hasProperty(Utils.EXO_CALENDAR_ID))
                calId = eventNode.getProperty(Utils.EXO_CALENDAR_ID).getString();
        }
        if (getCalendarMap().keySet().contains(calId)) {
            Calendar cal = getCalendarMap().get(calId);

            StringBuffer detail = new StringBuffer();
            String title = buildValue(Utils.EXO_SUMMARY, iter);
            detail.append(cal.getName());
            String url = buildLink(sc, siteKeys, calId, buildValue(Utils.EXO_ID, iter));
            String excerpt = buildValue(Utils.EXO_DESCRIPTION, iter);
            String detailValue = Utils.EMPTY_STR;
            String imageUrl = buildImageUrl(iter);
            detail.append(buildDetail(iter, calSeting.getTimeZone()));
            if (detail.length() > 0)
                detailValue = detail.toString();
            long relevancy = buildScore(iter);
            long date = buildDate(iter);
            TimeZone userTimezone = TimeZone.getTimeZone(calSeting.getTimeZone());
            CalendarSearchResult result = new CalendarSearchResult(url, title, excerpt, detailValue, imageUrl,
                    date, relevancy);
            result.setDataType(dataType);
            result.setTimeZoneName(calSeting.getTimeZone());
            result.setTimeZoneOffset(userTimezone.getOffset(date));
            if (CalendarEvent.TYPE_EVENT.equals(dataType)) {
                result.setFromDateTime(buildDate(iter, Utils.EXO_FROM_DATE_TIME).getTimeInMillis());
            } else if (CalendarEvent.TYPE_TASK.equals(dataType)) {
                result.setTaskStatus(buildValue(Utils.EXO_EVENT_STATE, iter));
            }
            return result;
        }
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Error when building result object from result data " + e);
    }
    return null;
}