Example usage for java.util TimeZone getRawOffset

List of usage examples for java.util TimeZone getRawOffset

Introduction

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

Prototype

public abstract int getRawOffset();

Source Link

Document

Returns the amount of time in milliseconds to add to UTC to get standard time in this time zone.

Usage

From source file:DateCache.java

private void setTzFormatString(final TimeZone tz) {
    int zIndex = _formatString.indexOf("ZZZ");
    if (zIndex >= 0) {
        String ss1 = _formatString.substring(0, zIndex);
        String ss2 = _formatString.substring(zIndex + 3);
        int tzOffset = tz.getRawOffset();

        StringBuffer sb = new StringBuffer(_formatString.length() + 10);
        sb.append(ss1);/*from ww w  . j a  v a 2 s .com*/
        sb.append("'");
        if (tzOffset >= 0)
            sb.append('+');
        else {
            tzOffset = -tzOffset;
            sb.append('-');
        }

        int raw = tzOffset / (1000 * 60); // Convert to seconds
        int hr = raw / 60;
        int min = raw % 60;

        if (hr < 10)
            sb.append('0');
        sb.append(hr);
        if (min < 10)
            sb.append('0');
        sb.append(min);
        sb.append('\'');

        sb.append(ss2);
        _tzFormatString = sb.toString();
    } else
        _tzFormatString = _formatString;
    setMinFormatString();
}

From source file:com.linemetrics.monk.api.ApiClient.java

public DataItem getLastValue(Number dataStreamId, final TDB tdb, final TimeZone tz) throws ApiException {

    try {/*from  ww w . jav  a 2s  . c  om*/
        URI uri = restclient.buildURI(getBaseUri() + "/lastvalue/" + dataStreamId,
                new HashMap<String, String>() {
                    {
                        put("tdb", "" + tdb.getMilliseconds());
                        put("time_offset", "" + (tz.getRawOffset() + tz.getDSTSavings()));
                    }
                });

        JSONObject result = restclient.get(uri);
        if (result.containsKey("data")) {
            return new DataItem(result.get("data"));
        }
    } catch (Exception ex) {
        throw new ApiException(
                "Unable to retrieve last value of dataStream (" + dataStreamId + "): " + ex.getMessage(), ex);
    }

    return null;
}

From source file:org.exoplatform.webservice.cs.calendar.CalendarWebservice.java

/**
 * listing up coming event or task given by current date time
 * @param username : current loged-in user
 * @param currentdatetime : current date time using ISO8601 format yyyyMMdd
 * @param type : event or task/*from   w  ww. j ava  2s.  c om*/
 * @return page list of event or task
 * @throws Exception : HTTPStatus.INTERNAL_ERROR , HTTPStatus.UNAUTHORIZED , HTTPStatus.NO_CONTENT
 */
@GET
@RolesAllowed("users")
@Path("/getissues/{currentdatetime}/{type}/{limit}")
public Response upcomingEvent(@PathParam("currentdatetime") String currentdatetime,
        @PathParam("type") String type, @PathParam("limit") int limit) throws Exception {

    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);

    try {

        //if(!isAuthorized(username)) {
        //return Response.status(HTTPStatus.UNAUTHORIZED).cacheControl(cacheControl).build();
        //}

        if (!(CalendarEvent.TYPE_EVENT.equalsIgnoreCase(type)
                || CalendarEvent.TYPE_TASK.equalsIgnoreCase(type))) {
            return Response.status(HTTPStatus.BAD_REQUEST).cacheControl(cacheControl).build();
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        java.util.Calendar fromCal = GregorianCalendar.getInstance();
        java.util.Calendar toCal = GregorianCalendar.getInstance();
        fromCal.setTime(sf.parse(currentdatetime));
        toCal.setTime(sf.parse(currentdatetime));
        CalendarService calService = (CalendarService) ExoContainerContext.getCurrentContainer()
                .getComponentInstanceOfType(CalendarService.class);
        EventQuery eventQuery = new EventQuery();
        eventQuery.setFromDate(fromCal);
        toCal.add(java.util.Calendar.HOUR_OF_DAY, 24);
        eventQuery.setToDate(toCal);
        eventQuery.setLimitedItems((int) limit);
        eventQuery.setOrderBy(new String[] { Utils.EXO_FROM_DATE_TIME });
        String username = ConversationState.getCurrent().getIdentity().getUserId();
        eventQuery.setEventType(type);
        EventPageList data = calService.searchEvent(username, eventQuery, null);
        CalendarSetting calSetting = calService.getCalendarSetting(username);
        String timezoneId = calSetting.getTimeZone();
        TimeZone userTimezone = TimeZone.getTimeZone(timezoneId);
        int timezoneOffset = userTimezone.getRawOffset() + userTimezone.getDSTSavings();
        if (data == null || data.getAll().isEmpty())
            return Response.status(HTTPStatus.NO_CONTENT).cacheControl(cacheControl).build();
        EventData eventData = new EventData();
        eventData.setInfo(data.getAll());
        eventData.setUserTimezoneOffset(Integer.toString(timezoneOffset));
        return Response.ok(eventData, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug(e.getMessage());
        return Response.status(HTTPStatus.INTERNAL_ERROR).cacheControl(cacheControl).build();
    }

}

From source file:it.cnr.icar.eric.server.common.Utility.java

public String createTimestamp() {
    // Get the time zone offset in +HH:mm format
    java.util.TimeZone tz = java.util.TimeZone.getDefault();

    float rawOffset = tz.getRawOffset() / 1000 / 60 / 60.0f;
    int offsetHr = (int) Math.abs(rawOffset);
    int offsetMin = (int) (rawOffset - offsetHr) * 60;

    String offset = (rawOffset > 0) ? "+" : "-";
    offset += ((offsetHr < 10) ? "0" : "");
    offset += offsetHr;/* w  w w .  jav  a2  s  . co m*/
    offset += ":";
    offset += ((offsetMin < 10) ? "0" : "");
    offset += offsetMin;

    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    return sdf.format(new java.util.Date()) + offset;
}

From source file:com.linemetrics.monk.api.ApiClient.java

public List<DataItem> getRange(Number dataStreamId, final long time_from, final long time_to, final TDB tdb,
        final TimeZone tz) throws ApiException {

    List<DataItem> list = new ArrayList<>();

    Map<String, String> reqParameters = new HashMap<String, String>() {
        {//from   w  ww . j ava 2 s.  co  m
            put("tdb", "" + tdb.getMilliseconds());
            put("time_to", "" + time_to);
            put("time_from", "" + time_from);
            put("time_offset", "" + (tz.getRawOffset() + tz.getDSTSavings()));
        }
    };
    String reqURl = getBaseUri() + "/data/" + dataStreamId;

    System.out.print("URL: " + reqURl + " -> " + reqParameters);

    int retries = MAX_RETRIES;
    boolean isError = false;

    while (retries-- >= 0) {

        if (isError) {
            System.out.println("WAIT CAUSE OF ERROR AND RETRY (" + (MAX_RETRIES - retries) + ")...");
            try {
                Thread.sleep(WAIT_MILLIS_AFTER_ERROR);
            } catch (InterruptedException iexp) {
                //                    iexp.printStackTrace();
            }
        }

        long millis = System.currentTimeMillis();
        isError = false;

        try {
            URI uri = restclient.buildURI(reqURl, reqParameters);

            JSONObject result = restclient.get(uri);

            if (result.containsKey("data") && result.get("data") instanceof List) {
                for (Object dataItem : (List) result.get("data")) {
                    DataItem di = new DataItem(dataItem);
                    di.setTimestampEnd(di.getTimestampStart() + tdb.getMilliseconds());
                    list.add(di);
                }

                if (list.isEmpty()) {
                    System.out.print(" DATA BUT EMPTY ");
                }
                break;
            } else {
                System.out.print(" NO DATA ");
                isError = true;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.print(" UNABLE: " + ex.getMessage());
            isError = true;
        } finally {
            System.out.println(": " + (System.currentTimeMillis() - millis) + "ms ");
        }
    }

    if (isError) {
        throw new ApiException("Unable to grab data");
    }

    Collections.sort(list, DataItemComparator.getInstance());

    DataItem currItem;

    Iterator<DataItem> itemIterator = list.iterator();
    while (itemIterator.hasNext()) {
        currItem = itemIterator.next();

        if (currItem.getTimestamp() < time_from || currItem.getTimestamp() > time_to) {

            itemIterator.remove();
        }
    }

    return list;
}

From source file:com.exadel.flamingo.flex.messaging.amf.io.AMF0Deserializer.java

/**
 * Reads date/*  w ww  .  j a  v a 2 s . c om*/
 *
 * @return
 * @throws IOException
 */
protected Date readDate() throws IOException {
    long ms = (long) inputStream.readDouble(); // Date in millis from 01/01/1970

    // here we have to read in the raw
    // timezone offset (which comes in minutes, but incorrectly signed),
    // make it millis, and fix the sign.
    int timeoffset = inputStream.readShort() * 60000 * -1; // now we have millis

    TimeZone serverTimeZone = TimeZone.getDefault();

    // now we subtract the current timezone offset and add the one that was passed
    // in (which is of the Flash client), which gives us the appropriate ms (i think)
    // -alon
    Calendar sent = new GregorianCalendar();
    sent.setTime((new Date(ms - serverTimeZone.getRawOffset() + timeoffset)));

    TimeZone sentTimeZone = sent.getTimeZone();

    // we have to handle daylight savings ms as well
    if (sentTimeZone.inDaylightTime(sent.getTime())) {
        //
        // Implementation note: we are trying to maintain compatibility
        // with J2SE 1.3.1
        //
        // As such, we can't use java.util.Calendar.getDSTSavings() here
        // 
        sent.setTime(new java.util.Date(sent.getTime().getTime() - 3600000));
    }

    return sent.getTime();
}

From source file:io.teak.sdk.Session.java

private void identifyUser() {
    final Session _this = this;

    new Thread(new Runnable() {
        public void run() {
            synchronized (_this.stateMutex) {
                HashMap<String, Object> payload = new HashMap<>();

                if (_this.state == State.UserIdentified) {
                    payload.put("do_not_track_event", Boolean.TRUE);
                }//w w  w. ja  v a  2  s . c  o  m

                TimeZone tz = TimeZone.getDefault();
                long rawTz = tz.getRawOffset();
                if (tz.inDaylightTime(new Date())) {
                    rawTz += tz.getDSTSavings();
                }
                long minutes = TimeUnit.MINUTES.convert(rawTz, TimeUnit.MILLISECONDS);
                String tzOffset = new DecimalFormat("#0.00").format(minutes / 60.0f);
                payload.put("timezone", tzOffset);

                String locale = Locale.getDefault().toString();
                payload.put("locale", locale);

                if (_this.deviceConfiguration.advertsingInfo != null) {
                    payload.put("android_ad_id", _this.deviceConfiguration.advertsingInfo.getId());
                    payload.put("android_limit_ad_tracking",
                            _this.deviceConfiguration.advertsingInfo.isLimitAdTrackingEnabled());
                }

                if (_this.facebookAccessToken != null) {
                    payload.put("access_token", _this.facebookAccessToken);
                }

                if (_this.launchedFromTeakNotifId != null) {
                    payload.put("teak_notif_id", Long.valueOf(_this.launchedFromTeakNotifId));
                }

                if (_this.launchedFromDeepLink != null) {
                    payload.put("deep_link", _this.launchedFromDeepLink);
                }

                if (_this.deviceConfiguration.gcmId != null) {
                    payload.put("gcm_push_key", _this.deviceConfiguration.gcmId);
                } else {
                    payload.put("gcm_push_key", "");
                }

                Log.d(LOG_TAG, "Identifying user: " + _this.userId);
                Log.d(LOG_TAG, "        Timezone: " + tzOffset);
                Log.d(LOG_TAG, "          Locale: " + locale);

                new Request("/games/" + _this.appConfiguration.appId + "/users.json", payload, _this) {
                    @Override
                    protected void done(int responseCode, String responseBody) {
                        try {
                            JSONObject response = new JSONObject(responseBody);

                            // TODO: Grab 'id' and 'game_id' from response and store for Parsnip

                            // Enable verbose logging if flagged
                            boolean enableVerboseLogging = response.optBoolean("verbose_logging");
                            if (Teak.debugConfiguration != null) {
                                Teak.debugConfiguration.setPreferenceForceDebug(enableVerboseLogging);
                            }

                            // Server requesting new push key.
                            if (response.optBoolean("reset_push_key", false)) {
                                _this.deviceConfiguration.reRegisterPushToken(_this.appConfiguration);
                            }

                            if (response.has("country_code")) {
                                _this.countryCode = response.getString("country_code");
                            }

                            // Prevent warning for 'do_not_track_event'
                            if (_this.state != State.UserIdentified) {
                                _this.setState(State.UserIdentified);
                            }
                        } catch (Exception ignored) {
                        }

                        super.done(responseCode, responseBody);
                    }
                }.run();
            }
        }
    }).start();
}

From source file:org.sleuthkit.autopsy.casemodule.Case.java

/**
 * Convert the Java timezone ID to the "formatted" string that can be
 * accepted by the C/C++ code. Example: "America/New_York" converted to
 * "EST5EDT", etc/*w  w  w.ja va 2 s. c o m*/
 *
 * @param timezoneID
 *
 * @return
 */
public static String convertTimeZone(String timezoneID) {

    TimeZone zone = TimeZone.getTimeZone(timezoneID);
    int offset = zone.getRawOffset() / 1000;
    int hour = offset / 3600;
    int min = (offset % 3600) / 60;

    DateFormat dfm = new SimpleDateFormat("z");
    dfm.setTimeZone(zone);
    boolean hasDaylight = zone.useDaylightTime();
    String first = dfm.format(new GregorianCalendar(2010, 1, 1).getTime()).substring(0, 3); // make it only 3 letters code
    String second = dfm.format(new GregorianCalendar(2011, 6, 6).getTime()).substring(0, 3); // make it only 3 letters code
    int mid = hour * -1;
    String result = first + Integer.toString(mid);
    if (min != 0) {
        result = result + ":" + Integer.toString(min);
    }
    if (hasDaylight) {
        result = result + second;
    }

    return result;
}

From source file:org.apache.cordova.core.Globalization.java

private JSONObject getDatePattern(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();

    try {//from  w w  w .j  av a  2 s .c o  m
        SimpleDateFormat fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                .getDateFormat(this.cordova.getActivity()); //default user preference for date
        SimpleDateFormat fmtTime = (SimpleDateFormat) android.text.format.DateFormat
                .getTimeFormat(this.cordova.getActivity()); //default user preference for time

        String fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); //default SHORT date/time format. ex. dd/MM/yyyy h:mm a

        //get Date value + options (if available)
        if (options.getJSONObject(0).has(OPTIONS)) {
            //options were included

            JSONObject innerOptions = options.getJSONObject(0).getJSONObject(OPTIONS);
            //get formatLength option
            if (!innerOptions.isNull(FORMATLENGTH)) {
                String fmtOpt = innerOptions.getString(FORMATLENGTH);
                if (fmtOpt.equalsIgnoreCase(MEDIUM)) {//medium
                    fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                            .getMediumDateFormat(this.cordova.getActivity());
                } else if (fmtOpt.equalsIgnoreCase(LONG) || fmtOpt.equalsIgnoreCase(FULL)) { //long/full
                    fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                            .getLongDateFormat(this.cordova.getActivity());
                }
            }

            //return pattern type
            fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern();
            if (!innerOptions.isNull(SELECTOR)) {
                String selOpt = innerOptions.getString(SELECTOR);
                if (selOpt.equalsIgnoreCase(DATE)) {
                    fmt = fmtDate.toLocalizedPattern();
                } else if (selOpt.equalsIgnoreCase(TIME)) {
                    fmt = fmtTime.toLocalizedPattern();
                }
            }
        }

        //TimeZone from users device
        //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method
        TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());

        obj.put("pattern", fmt);
        obj.put("timezone",
                tz.getDisplayName(tz.inDaylightTime(Calendar.getInstance().getTime()), TimeZone.SHORT));
        obj.put("utc_offset", tz.getRawOffset() / 1000);
        obj.put("dst_offset", tz.getDSTSavings() / 1000);
        return obj;

    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
    }
}

From source file:org.apache.cordova.Globalization.java

private JSONObject getDatePattern(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();

    try {/* w  w w  .  ja  v a2  s .  c  om*/
        SimpleDateFormat fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                .getDateFormat(this.cordova.getActivity()); //default user preference for date
        SimpleDateFormat fmtTime = (SimpleDateFormat) android.text.format.DateFormat
                .getTimeFormat(this.cordova.getActivity()); //default user preference for time

        String fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); //default SHORT date/time format. ex. dd/MM/yyyy h:mm a

        //get Date value + options (if available)
        boolean test = options.getJSONObject(0).has(OPTIONS);
        if (options.getJSONObject(0).has(OPTIONS)) {
            //options were included
            JSONObject innerOptions = options.getJSONObject(0).getJSONObject(OPTIONS);
            //get formatLength option
            if (!innerOptions.isNull(FORMATLENGTH)) {
                String fmtOpt = innerOptions.getString(FORMATLENGTH);
                if (fmtOpt.equalsIgnoreCase(MEDIUM)) {//medium
                    fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                            .getMediumDateFormat(this.cordova.getActivity());
                } else if (fmtOpt.equalsIgnoreCase(LONG) || fmtOpt.equalsIgnoreCase(FULL)) { //long/full
                    fmtDate = (SimpleDateFormat) android.text.format.DateFormat
                            .getLongDateFormat(this.cordova.getActivity());
                }
            }

            //return pattern type
            fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern();
            if (!innerOptions.isNull(SELECTOR)) {
                String selOpt = innerOptions.getString(SELECTOR);
                if (selOpt.equalsIgnoreCase(DATE)) {
                    fmt = fmtDate.toLocalizedPattern();
                } else if (selOpt.equalsIgnoreCase(TIME)) {
                    fmt = fmtTime.toLocalizedPattern();
                }
            }
        }

        //TimeZone from users device
        //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method
        TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());

        obj.put("pattern", fmt);
        obj.put("timezone",
                tz.getDisplayName(tz.inDaylightTime(Calendar.getInstance().getTime()), TimeZone.SHORT));
        obj.put("utc_offset", tz.getRawOffset() / 1000);
        obj.put("dst_offset", tz.getDSTSavings() / 1000);
        return obj;

    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
    }
}