Example usage for java.util Calendar setTimeZone

List of usage examples for java.util Calendar setTimeZone

Introduction

In this page you can find the example usage for java.util Calendar setTimeZone.

Prototype

public void setTimeZone(TimeZone value) 

Source Link

Document

Sets the time zone with the given time zone value.

Usage

From source file:org.jbpm.bpel.xml.util.DatatypeUtil.java

/**
 * Parses the lexical representation of a date/dateTime as per the XML Schema
 * recommendation.//w  w  w .  j av a2 s.com
 * @param text the lexical representation of a date/dateTime
 * @return the date/dateTime the text represents
 * @see <a href="http://www.w3.org/TR/xmlschema-2/#dateTime"> XML Schema Part
 * 2: Datatypes &sect;3.2.7</a>
 */
public static Calendar parseDateTime(String text) {
    Matcher matcher = dateTimePattern.matcher(text);
    if (matcher.matches()) {
        Calendar dateTime = Calendar.getInstance();
        // calendar is initialized with the current time; must be cleared
        dateTime.clear();
        // group 1: year
        dateTime.set(Calendar.YEAR, Integer.parseInt(matcher.group(1)));
        // group 2: month; the month field is zero-based
        dateTime.set(Calendar.MONTH, Integer.parseInt(matcher.group(2)) - 1);
        // group 3: day
        dateTime.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(3)));
        // group 4: hour
        String group = matcher.group(4);
        if (group != null) {
            // if the hour is present, so are minutes and seconds
            dateTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(group));
            // group 5: minute
            dateTime.set(Calendar.MINUTE, Integer.parseInt(matcher.group(5)));
            // group 6: second
            dateTime.set(Calendar.SECOND, Integer.parseInt(matcher.group(6)));
            // group 7: milliseconds
            group = matcher.group(7);
            if (group != null) {
                dateTime.set(Calendar.MILLISECOND, Integer.parseInt(group));
            }
        }
        // group 8: timezone
        group = matcher.group(8);
        if (group != null) {
            TimeZone timeZone;
            if (group.equals("Z")) {
                // "Z" means "the zero-length duration timezone"
                timeZone = TimeZone.getTimeZone("GMT+00:00");
            } else {
                timeZone = TimeZone.getTimeZone("GMT" + group);
            }
            dateTime.setTimeZone(timeZone);
        }
        // the schema recommendation mandates strict date interpretation
        dateTime.setLenient(false);
        return dateTime;
    }
    log.debug("invalid dateTime lexical representation: " + text);
    return null;
}

From source file:org.apache.axis2.databinding.utils.ConverterUtil.java

public static String convertToString(Calendar value) {
    if (isCustomClassPresent) {
        return invokeToStringMethod(value, Calendar.class);
    } else {//  ww  w . j a va  2s  .c om
        // lexical form of the calendar is '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?
        if (value.get(Calendar.ZONE_OFFSET) == -1) {
            value.setTimeZone(TimeZone.getDefault());
        }
        StringBuffer dateString = new StringBuffer(28);
        appendDate(dateString, value);
        dateString.append("T");
        //adding hours
        appendTime(value, dateString);
        appendTimeZone(value, dateString);
        return dateString.toString();
    }
}

From source file:org.eclipsetrader.yahoojapan.internal.core.connector.SnapshotConnector.java

protected Date getDateValue(String dateValue, String timeValue) {
    String date = stripQuotes(dateValue);
    String time = stripQuotes(timeValue);

    if (date.indexOf("N/A") != -1 && time.indexOf("N/A") != -1) {
        return null;
    }//from w ww  .  j  a v a 2s . c o m

    try {
        if (date.indexOf("N/A") != -1) {
            date = dateParser.format(Calendar.getInstance(timeZone).getTime());
        }
        if (time.indexOf("N/A") != -1) {
            time = timeParser.format(Calendar.getInstance(timeZone).getTime());
        }

        Calendar c = Calendar.getInstance();
        int y = c.get(Calendar.YEAR);
        c.setTime(dateTimeParser.parse(date + " " + time)); //$NON-NLS-1$
        c.set(Calendar.YEAR, y);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.setTimeZone(TimeZone.getDefault());
        if (c.get(Calendar.YEAR) < 70) {
            c.add(Calendar.YEAR, 2000);
        }

        return c.getTime();
    } catch (ParseException e) {
        Status status = new Status(IStatus.ERROR, YahooJapanActivator.PLUGIN_ID, 0,
                "Error parsing date/time values", e);
        YahooJapanActivator.log(status);
    }

    return null;
}

From source file:org.croudtrip.fragments.join.JoinDrivingFragment.java

private void showJoinedTrip(List<JoinTripRequest> requests) {

    if (requests == null || requests.isEmpty()) {
        Timber.e("List<JoinTripRequest> is empty or doesn't exist");
        return;/* w w  w. j a v  a  2  s  .c  o m*/
    }

    if (flMap.getVisibility() == View.VISIBLE) {
        drawRoutesOnMap(requests);
    }

    // Show drivers
    for (JoinTripRequest r : requests) {
        adapter.updateRequest(r);
    }

    progressBarDrivers.setVisibility(View.GONE);

    // Show correct plural of drivers
    int numDrivers = adapter.getNumDrivers();
    Resources res = getResources();
    tvMyDrivers.setText(res.getQuantityString(R.plurals.join_trip_results_my_drivers, numDrivers, numDrivers));

    // TODO: for first/next driver
    // Show arrival time
    String dateAsString = "";
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getDefault());
    calendar.setTimeInMillis(1000 * (requests.get(0).getEstimatedArrivalTimestamp()));

    //Display remaining time in the format hh:mm
    if ((calendar.get(Calendar.HOUR_OF_DAY) < 10) && (calendar.get((Calendar.MINUTE)) < 10))
        dateAsString = "0" + calendar.get(Calendar.HOUR_OF_DAY) + ":0" + calendar.get(Calendar.MINUTE);
    else if (calendar.get(Calendar.HOUR_OF_DAY) < 10)
        dateAsString = "0" + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
    else if (calendar.get((Calendar.MINUTE)) < 10)
        dateAsString = calendar.get(Calendar.HOUR_OF_DAY) + ":0" + calendar.get(Calendar.MINUTE);
    else
        dateAsString = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);

    tvPickupTime.setText(dateAsString);
}

From source file:org.openanzo.test.client.TestDateTime.java

/**
 * The java.util.Calendar API makes it tricky to get a calendar initialized in a predictable state since most ways to create it use the system default time
 * zone, locale, and sometimes the current time.
 * /*from www.java 2  s  . c om*/
 * This method helps ensure getting a calendar object that is more predictable across different systems.
 * 
 * @return a new fairly clean Calendar, ready for you to put your dirty paws all over it.
 */
private Calendar getCleanCalendar() {
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(DateUtils.UTC_TIME_ZONE);
    cal.clear();
    cal.setLenient(false);
    return cal;
}

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

/**
 * Determine how many hours is on the date of n-th dataset instance. <p> It depends on: <p> 1. Data set frequency
 * <p> 2. Data set Time unit (day, month, minute) <p> 3. Data set Time zone/DST <p> 4. End Day/Month flag <p> 5.
 * Data set initial instance <p> 6. Action Creation Time
 *
 * @param n instance count <p> domain: n is integer
 * @return number of hours on that day <p> returns -1 means n-th instance is earlier than Initial-Instance of DS
 * @throws Exception//from   w  w w  .  j  ava2  s .co  m
 */
public static int ph2_coord_hoursInDay(int n) throws Exception {
    int datasetFrequency = (int) getDSFrequency();
    // /Calendar nominalInstanceCal =
    // getCurrentInstance(getActionCreationtime());
    Calendar nominalInstanceCal = getEffectiveNominalTime();
    if (nominalInstanceCal == null) {
        return -1;
    }
    nominalInstanceCal.add(getDSTimeUnit().getCalendarUnit(), datasetFrequency * n);
    /*
     * if (nominalInstanceCal.getTime().compareTo(getInitialInstance()) < 0)
     * { return -1; }
     */
    nominalInstanceCal.setTimeZone(getDatasetTZ());// Use Dataset TZ
    // DateUtils.moveToEnd(nominalInstanceCal, getDSEndOfFlag());
    return DateUtils.hoursInDay(nominalInstanceCal);
}

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

/**
 * Calculate number of days in one month for n-th dataset instance. <p> It depends on: <p> 1. Data set frequency .
 * <p> 2. Data set Time unit (day, month, minute) <p> 3. Data set Time zone/DST <p> 4. End Day/Month flag <p> 5.
 * Data set initial instance <p> 6. Action Creation Time
 *
 * @param n instance count. domain: n is integer
 * @return number of days in that month <p> returns -1 means n-th instance is earlier than Initial-Instance of DS
 * @throws Exception//from  ww w. j  a v a2  s. co m
 */
public static int ph2_coord_daysInMonth(int n) throws Exception {
    int datasetFrequency = (int) getDSFrequency();// in minutes
    // Calendar nominalInstanceCal =
    // getCurrentInstance(getActionCreationtime());
    Calendar nominalInstanceCal = getEffectiveNominalTime();
    if (nominalInstanceCal == null) {
        return -1;
    }
    nominalInstanceCal.add(getDSTimeUnit().getCalendarUnit(), datasetFrequency * n);
    /*
     * if (nominalInstanceCal.getTime().compareTo(getInitialInstance()) < 0)
     * { return -1; }
     */
    nominalInstanceCal.setTimeZone(getDatasetTZ());// Use Dataset TZ
    // DateUtils.moveToEnd(nominalInstanceCal, getDSEndOfFlag());
    return nominalInstanceCal.getActualMaximum(Calendar.DAY_OF_MONTH);
}

From source file:org.openhab.binding.keba.handler.KeContactHandler.java

protected void onRead(ByteBuffer byteBuffer) {
    String response = new String(byteBuffer.array(), 0, byteBuffer.limit());
    response = StringUtils.chomp(response);

    if (response.contains("TCH-OK")) {
        // ignore confirmation messages which are not JSON
        return;/*from  w w  w  .  j  a va  2 s .c  om*/
    }

    try {
        JsonObject readObject = parser.parse(response).getAsJsonObject();

        for (Entry<String, JsonElement> entry : readObject.entrySet()) {
            switch (entry.getKey()) {
            case "Product": {
                Map<String, String> properties = editProperties();
                String product = entry.getValue().getAsString().trim();
                properties.put(CHANNEL_MODEL, product);
                updateProperties(properties);
                if (product.contains("P20")) {
                    type = KebaType.P20;
                } else if (product.contains("P30")) {
                    type = KebaType.P30;
                }
                series = KebaSeries.getSeries(product.substring(13, 14).charAt(0));
                break;
            }
            case "Serial": {
                Map<String, String> properties = editProperties();
                properties.put(CHANNEL_SERIAL, entry.getValue().getAsString());
                updateProperties(properties);
                break;
            }
            case "Firmware": {
                Map<String, String> properties = editProperties();
                properties.put(CHANNEL_FIRMWARE, entry.getValue().getAsString());
                updateProperties(properties);
                firmware = KebaFirmware.getFirmware(entry.getValue().getAsString());
                break;

            }
            case "Plug": {
                int state = entry.getValue().getAsInt();
                switch (state) {
                case 0: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.OFF);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF);
                    break;
                }
                case 1: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF);
                    break;
                }
                case 3: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.ON);
                    break;
                }
                case 5: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.ON);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF);
                    break;
                }
                case 7: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.ON);
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.ON);
                    break;
                }
                }
                break;
            }
            case "State": {
                State newState = new DecimalType(entry.getValue().getAsInt());
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_STATE), newState);
                break;
            }
            case "Enable sys": {
                int state = entry.getValue().getAsInt();
                switch (state) {
                case 1: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_ENABLED), OnOffType.ON);
                    break;
                }
                default: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_ENABLED), OnOffType.OFF);
                    break;
                }
                }
                break;
            }
            case "Curr HW": {
                int state = entry.getValue().getAsInt();
                maxSystemCurrent = state;
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_SYSTEM_CURRENT), newState);
                if (maxSystemCurrent < maxPresetCurrent) {
                    sendCommand("curr " + String.valueOf(maxSystemCurrent));
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT),
                            new DecimalType(maxSystemCurrent));
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT_RANGE),
                            new PercentType((maxSystemCurrent - 6000) * 100 / (maxSystemCurrent - 6000)));
                }
                break;
            }
            case "Curr user": {
                int state = entry.getValue().getAsInt();
                maxPresetCurrent = state;
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT),
                        new DecimalType(state));
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT_RANGE),
                        new PercentType((state - 6000) * 100 / (maxSystemCurrent - 6000)));
                break;
            }
            case "Curr FS": {
                int state = entry.getValue().getAsInt();
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_FAILSAFE_CURRENT), newState);
                break;
            }
            case "Output": {
                int state = entry.getValue().getAsInt();
                switch (state) {
                case 1: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_OUTPUT), OnOffType.ON);
                    break;
                }
                default: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_OUTPUT), OnOffType.OFF);
                    break;
                }
                }
                break;
            }
            case "Input": {
                int state = entry.getValue().getAsInt();
                switch (state) {
                case 1: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), OnOffType.ON);
                    break;
                }
                default: {
                    updateState(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), OnOffType.OFF);
                    break;
                }
                }
                break;
            }
            case "Sec": {
                long state = entry.getValue().getAsLong();

                Calendar uptime = Calendar.getInstance();
                uptime.setTimeZone(TimeZone.getTimeZone("GMT"));
                uptime.setTimeInMillis(state * 1000);
                SimpleDateFormat pFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                pFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));

                updateState(new ChannelUID(getThing().getUID(), CHANNEL_UPTIME),
                        new DateTimeType(pFormatter.format(uptime.getTime())));
                break;
            }
            case "U1": {
                int state = entry.getValue().getAsInt();
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_U1), newState);
                break;
            }
            case "U2": {
                int state = entry.getValue().getAsInt();
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_U2), newState);
                break;
            }
            case "U3": {
                int state = entry.getValue().getAsInt();
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_U3), newState);
                break;
            }
            case "I1": {
                int state = entry.getValue().getAsInt();
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_I1), newState);
                break;
            }
            case "I2": {
                int state = entry.getValue().getAsInt();
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_I2), newState);
                break;
            }
            case "I3": {
                int state = entry.getValue().getAsInt();
                State newState = new DecimalType(state);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_I3), newState);
                break;
            }
            case "P": {
                long state = entry.getValue().getAsLong();
                State newState = new DecimalType(state / 1000);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_POWER), newState);
                break;
            }
            case "PF": {
                int state = entry.getValue().getAsInt();
                State newState = new PercentType(state / 10);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_POWER_FACTOR), newState);
                break;
            }
            case "E pres": {
                long state = entry.getValue().getAsLong();
                State newState = new DecimalType(state / 10);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_SESSION_CONSUMPTION), newState);
                break;
            }
            case "E total": {
                long state = entry.getValue().getAsLong();
                State newState = new DecimalType(state / 10);
                updateState(new ChannelUID(getThing().getUID(), CHANNEL_TOTAL_CONSUMPTION), newState);
                break;
            }
            }
        }

    } catch (JsonParseException e) {
        logger.debug("Invalid JSON data will be ignored: '{}'", response);
    }
}

From source file:org.imos.abos.netcdf.NetCDFfile.java

public void writeCoordinateVariables(ArrayList<Timestamp> timeArray) {
    if (timeIsDoubleDays) {
        logger.info(//from w  ww.j  a v a2s  .c  o  m
                "writeCoordinateVariables timeArray " + timeArray.size() + " timeDim " + timeDim.toString());

        times = new ArrayDouble.D1(timeDim.getLength());
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(tz);
        for (int i = 0; i < timeDim.getLength(); i++) {
            Timestamp ts = timeArray.get(i);
            long offsetTime = (ts.getTime() - anchorTime) / 1000;
            double elapsedHours = ((double) offsetTime) / (3600 * 24);

            times.setDouble(i, elapsedHours);
        }
    } else {
        times = new ArrayInt.D1(timeDim.getLength());
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(tz);
        for (int i = 0; i < timeDim.getLength(); i++) {
            Timestamp ts = timeArray.get(i);
            long offsetTime = (ts.getTime() - anchorTime) / 1000;
            int elapsedHours = (int) offsetTime / 3600;
            times.setInt(i, elapsedHours);
        }
    }

    ArrayList<Dimension> tdlist = new ArrayList<Dimension>();
    tdlist.add(timeDim);
    if (timeIsDoubleDays) {
        vTime = dataFile.addVariable(null, "TIME", DataType.DOUBLE, tdlist);
    } else {
        vTime = dataFile.addVariable(null, "TIME", DataType.INT, tdlist);
    }

    if (addTimeBnds) {
        ArrayList<Dimension> tdbndsList = new ArrayList<Dimension>();
        tdbndsList.add(timeDim);
        tdbndsList.add(bndsDim);
        timesBnds = new ArrayDouble.D2(timeDim.getLength(), 2);
        vTimeBnds = dataFile.addVariable(null, "TIME_bnds", DataType.DOUBLE, tdbndsList);
    }
}

From source file:org.sakaiproject.signup.tool.jsf.SignupUIBaseBean.java

private Date getUserTimezonePreferenceDate(Date dateBasedOnServerTimezone) {
    /*//ww  w.ja  v  a2s  .c om
     * Since the external-calendar-service don't honor the timezone information (in
     * iCal file), which is passed by Date object. Here, we just convert it manually here.
     * Once the external-claendar-service can do the job, this method can be removed.
     */
    TimeService timeService = sakaiFacade.getTimeService();
    TimeZone currentUserTimeZone = timeService.getLocalTimeZone();

    Calendar cal = Calendar.getInstance();
    cal.setTime(dateBasedOnServerTimezone);
    cal.setTimeZone(currentUserTimeZone);

    //get user Pref display hour, day, month and year
    int userPrefMinute = cal.get(cal.MINUTE);
    int userPrefHour = cal.get(cal.HOUR_OF_DAY);
    int userPrefDay = cal.get(cal.DAY_OF_MONTH);
    int userPrefMonth = cal.get(cal.MONTH);
    int userPreYear = cal.get(cal.YEAR);

    Calendar calNew = Calendar.getInstance();
    calNew.setTime(dateBasedOnServerTimezone);
    calNew.set(cal.MINUTE, userPrefMinute);
    calNew.set(cal.HOUR_OF_DAY, userPrefHour);
    calNew.set(cal.DAY_OF_MONTH, userPrefDay);
    calNew.set(cal.MONTH, userPrefMonth);
    calNew.set(cal.YEAR, userPreYear);
    return calNew.getTime();
}