Example usage for java.util Calendar DST_OFFSET

List of usage examples for java.util Calendar DST_OFFSET

Introduction

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

Prototype

int DST_OFFSET

To view the source code for java.util Calendar DST_OFFSET.

Click Source Link

Document

Field number for get and set indicating the daylight saving offset in milliseconds.

Usage

From source file:com.krawler.common.timezone.Timezone.java

public static Date getGmtDate(Date userDate) throws ServiceException {
    Date cmpdate = new Date();
    //try{/* w  w w .j a  va 2s. co m*/
    Calendar calInstance = Calendar.getInstance();

    int gmtoffset = calInstance.get(Calendar.DST_OFFSET) + calInstance.get(Calendar.ZONE_OFFSET);
    //SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm a");
    //String cmp = sdf.format(userDate);

    cmpdate = new Date(userDate.getTime() - gmtoffset);

    /*} catch(ParseException e){
    throw ServiceException.FAILURE("Timezone.getGmtDate", e);
    }*/
    return cmpdate;
}

From source file:org.yccheok.jstock.engine.GoogleStockHistoryServer.java

private boolean parse(String respond) {
    historyDatabase.clear();//  www. j av a 2s  .c  o m
    timestamps.clear();

    final long startTimeInMilli = this.duration.getStartDate().getTime().getTime();
    final long endTimeInMilli = this.duration.getEndDate().getTime().getTime();

    String[] stockDatas = respond.split("\r\n|\r|\n");

    double previousClosePrice = Double.MAX_VALUE;
    long time = 0;

    Symbol symbol = Symbol.newInstance(code.toString());
    String name = symbol.toString();
    Stock.Board board = Stock.Board.Unknown;
    Stock.Industry industry = Stock.Industry.Unknown;
    Calendar calendar = null;
    boolean initialized = false;

    long TIMEZONE_OFFSET = 0;

    for (String stockData : stockDatas) {
        // NYSE : TIMEZONE_OFFSET=-300

        if (stockData.isEmpty()) {
            continue;
        }

        char c = stockData.charAt(0);
        if (c != 'a' && false == Character.isDigit(c)) {
            if (stockData.startsWith("TIMEZONE_OFFSET")) {
                String[] fields = stockData.split("=");
                if (fields.length == 2) {
                    try {
                        TIMEZONE_OFFSET = Long.parseLong(fields[1]);
                    } catch (NumberFormatException ex) {
                        log.error(null, ex);
                    }
                }
            }
            continue;
        }

        String[] fields = stockData.split(",");

        // DATE,CLOSE,HIGH,LOW,OPEN,VOLUME
        if (fields.length < 6) {
            continue;
        }

        long currentTime = 0;

        final String fields0 = fields[0];
        if (fields0.charAt(0) == 'a') {
            if (fields0.length() > 1) {
                String timeStr = fields0.substring(1);
                try {
                    time = Long.parseLong(timeStr);
                } catch (NumberFormatException ex) {
                    log.error(null, ex);
                    continue;
                }

                currentTime = time;
            }
        } else {
            int index = 0;
            try {
                index = Integer.parseInt(fields0);
            } catch (NumberFormatException ex) {
                log.error(null, ex);
                continue;
            }

            currentTime = time + (index * 60 * 60 * 24);
        }

        if (initialized == false) {
            try {
                Stock stock = stockServer.getStock(googleCode);
                symbol = stock.symbol;
                name = stock.getName();
                board = stock.getBoard();
                industry = stock.getIndustry();
            } catch (StockNotFoundException exp) {
                log.error(null, exp);
            }

            calendar = Calendar.getInstance();

            initialized = true;
        }

        long currentTimeInMilli = currentTime * 1000;

        // Convert it to local time respect to stock exchange.
        // TIMEZONE_OFFSET is in minute.
        currentTimeInMilli = currentTimeInMilli + (TIMEZONE_OFFSET * 60 * 1000);

        // Remove time information, by resetting it to 00:00
        currentTimeInMilli = currentTimeInMilli / 1000 / 24 / 60 / 60;
        currentTimeInMilli = currentTimeInMilli * 60 * 60 * 24 * 1000;

        // Make it as local timestamp.
        //
        // For instance, Greenwich is 1:30pm right now.
        // We want to make Malaysia 1:30pm right now.
        //
        // That's why we are having -ve.
        calendar.setTimeInMillis(currentTimeInMilli);
        int offset = -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
        currentTimeInMilli = currentTimeInMilli + offset;

        if (currentTimeInMilli < startTimeInMilli) {
            continue;
        }
        if (currentTimeInMilli > endTimeInMilli) {
            break;
        }

        double closePrice = 0.0;
        double highPrice = 0.0;
        double lowPrice = 0.0;
        double prevPrice = 0.0;
        double openPrice = 0.0;
        // TODO: CRITICAL LONG BUG REVISED NEEDED.
        long volume = 0;
        //double adjustedClosePrice = 0.0;

        try {
            closePrice = Double.parseDouble(fields[1]);
            highPrice = Double.parseDouble(fields[2]);
            lowPrice = Double.parseDouble(fields[3]);
            openPrice = Double.parseDouble(fields[4]);
            prevPrice = (previousClosePrice == Double.MAX_VALUE) ? 0 : previousClosePrice;

            // TODO: CRITICAL LONG BUG REVISED NEEDED.
            volume = Long.parseLong(fields[5]);
            //adjustedClosePrice = Double.parseDouble(fields[6]);
        } catch (NumberFormatException exp) {
            log.error(null, exp);
        }

        double changePrice = (previousClosePrice == Double.MAX_VALUE) ? 0 : closePrice - previousClosePrice;
        double changePricePercentage = ((previousClosePrice == Double.MAX_VALUE) || (previousClosePrice == 0.0))
                ? 0
                : changePrice / previousClosePrice * 100.0;

        Stock stock = new Stock(code, symbol, name, board, industry, prevPrice, openPrice,
                closePrice, /* Last Price. */
                highPrice, lowPrice, volume, changePrice, changePricePercentage, 0, 0.0, 0, 0.0, 0, 0.0, 0, 0.0,
                0, 0.0, 0, 0.0, 0, currentTimeInMilli);

        historyDatabase.put(currentTimeInMilli, stock);

        // Something we do not understand Google server.
        //if (timestamps.isEmpty()) {
        timestamps.add(currentTimeInMilli);
        //} else {
        //    if (timestamps.get(timestamps.size() - 1) != currentTimeInMilli) {
        //        timestamps.add(currentTimeInMilli);
        //    }
        //}
        previousClosePrice = closePrice;
    }

    return (historyDatabase.size() > 0);
}

From source file:org.openbravo.erpCommon.utility.OBDateUtils.java

/**
 * Returns a new Date converted to UTC//ww w.ja v  a  2  s. c o  m
 * 
 * @param date
 *          Date to be converted to UTC
 * 
 */
public static Date convertDateToUTC(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    int gmtMillisecondOffset = (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
    calendar.add(Calendar.MILLISECOND, -gmtMillisecondOffset);

    return calendar.getTime();
}

From source file:org.openbravo.client.kernel.reference.TimeUIDefinition.java

@Override
// Value is a date in local time format
public synchronized Object createFromClassicString(String value) {
    try {/*from   www .  ja  va 2 s  .  com*/
        if (value == null || value.length() == 0 || value.equals("null")) {
            return null;
        }

        final Date localDate = getClassicFormat().parse(value);
        // If a date is not specified, 01-01-1970 will be set by default
        // Today's date should be returned
        Calendar now = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(localDate);
        calendar.set(Calendar.DATE, now.get(Calendar.DATE));
        calendar.set(Calendar.MONTH, now.get(Calendar.MONTH));
        calendar.set(Calendar.YEAR, now.get(Calendar.YEAR));

        // Applies the zone offset and the dst offset to convert the time from local to UTC
        int gmtMillisecondOffset = (now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET));
        calendar.add(Calendar.MILLISECOND, -gmtMillisecondOffset);

        return xmlTimeFormat.format(calendar.getTime());
    } catch (Exception e) {
        throw new OBException("Exception when handling value " + value, e);
    }
}

From source file:org.kuali.rice.core.impl.datetime.DateTimeServiceImpl.java

public int dateDiff(Date startDate, Date endDate, boolean inclusive) {
    Calendar startDateCalendar = Calendar.getInstance();
    startDateCalendar.setTime(startDate);

    Calendar endDateCalendar = Calendar.getInstance();
    endDateCalendar.setTime(endDate);//w  ww . ja v  a2  s  .  c  om

    int startDateOffset = -(startDateCalendar.get(Calendar.ZONE_OFFSET)
            + startDateCalendar.get(Calendar.DST_OFFSET)) / (60 * 1000);

    int endDateOffset = -(endDateCalendar.get(Calendar.ZONE_OFFSET) + endDateCalendar.get(Calendar.DST_OFFSET))
            / (60 * 1000);

    if (startDateOffset > endDateOffset) {
        startDateCalendar.add(Calendar.MINUTE, endDateOffset - startDateOffset);
    }

    if (inclusive) {
        startDateCalendar.add(Calendar.DATE, -1);
    }

    int dateDiff = Integer.parseInt(DurationFormatUtils.formatDuration(
            endDateCalendar.getTimeInMillis() - startDateCalendar.getTimeInMillis(), "d", true));

    return dateDiff;
}

From source file:org.energy_home.jemma.internal.ah.eh.esp.ESPContainersDataUtils.java

public static boolean checkDuration(Calendar c, long startTime, long duration, int resolution) {
    // TODO: check for a more efficient implementation
    long now = System.currentTimeMillis();
    long endTime;

    if (startTime + duration >= now)
        // Test added to manage produced energy forecast (it is assumed that hourly forecast data are already normalized)
        return true;

    Long initialConfigurationTime = ESPConfiguration.getInitialConfigurationTime();
    long initialTime = initialConfigurationTime != null ? initialConfigurationTime.longValue()
            : DateUtils.DEFAULT_INITIAL_TIME;

    // Partial values min error limit are calculated using initialTime for
    // installation hour, day and month
    // Partial values max error limit are calculated using now for current
    // hour, day and month
    switch (resolution) {
    case ESPService.MONTH_RESOLUTION:
        startTime = getNormalizedStartTime(c, startTime, ESPService.MONTH_RESOLUTION);
        endTime = getNormalizedEndTime(c, startTime, ESPService.MONTH_RESOLUTION);
        break;/*  w ww.  ja v a  2  s.  c  o  m*/
    case ESPService.DAY_RESOLUTION:
        startTime = getNormalizedStartTime(c, startTime, ESPService.DAY_RESOLUTION);
        endTime = getNormalizedEndTime(c, startTime, ESPService.DAY_RESOLUTION);
        break;
    case ESPService.HOUR_RESOLUTION:
        startTime = getNormalizedStartTime(c, startTime, ESPService.HOUR_RESOLUTION);
        endTime = getNormalizedEndTime(c, startTime, ESPService.HOUR_RESOLUTION);
        break;
    default:
        return false;
    }
    startTime = Math.max(startTime, initialTime);
    endTime = Math.min(now, endTime);
    long maxExpectedDuration = endTime - startTime + 1;
    if (endTime == now)
        endTime = now - FIVE_MINUTES_IN_MILLISEC;
    long minExpectedDuration = endTime - startTime + 1;
    if (minExpectedDuration < 0)
        minExpectedDuration = 0;
    boolean result = duration >= minExpectedDuration * (1 - DURATION_ERROR_TOLERANCE)
            && duration <= maxExpectedDuration * (1 + DURATION_ERROR_TOLERANCE);
    // Check for DST change
    if (!result && resolution == ESPService.HOUR_RESOLUTION) {
        c.setTimeInMillis(startTime - 1);
        int startDst = c.get(Calendar.DST_OFFSET);
        c.setTimeInMillis(endTime + 1);
        int endDst = c.get(Calendar.DST_OFFSET);
        int dstOffset = endDst - startDst;
        // TODO: patch to be reviewed when hap server is modified (correct test should be dstOffset < 0) 
        if (dstOffset != 0) {
            maxExpectedDuration = maxExpectedDuration + Math.abs(dstOffset);
            result = duration >= minExpectedDuration * (1 - DURATION_ERROR_TOLERANCE)
                    && duration <= maxExpectedDuration * (1 + DURATION_ERROR_TOLERANCE);
        }
    }
    return result;
}

From source file:org.opencastproject.capture.impl.ConfigurationManager.java

/**
 * Retrieve property for configuration./*ww  w . j a  va  2s.com*/
 * 
 * @param key
 *          the key to retrieve from the property list.
 * @return the value corresponding to the key.
 */
public String getItem(String key) {
    if (key == null) {
        return null;
    } else if (StringUtils.equals(key, "capture.device.timezone.offset")) {
        Calendar cal = Calendar.getInstance();
        return Long.toString((cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET))
                / (1 * CaptureParameters.MINUTES * CaptureParameters.MILLISECONDS));
    } else if (StringUtils.equals(key, "capture.device.timezone")) {
        return TimeZone.getDefault().getID();
    } else {
        return properties.getProperty(key);
    }
}

From source file:Currently.java

/**
 * Ignores any internal date format, and tries to show a complete
 * date/timp stamp in extended ISO 8601 format. UTC time (Zulu time)
 * or a local timezone will be used.<p>
 *
 * <table border=1>//from  ww w  .j  a v a  2 s  .c  om
 * <tr><th>zone</th><th>format</th><th>fraction</td><th>example</th></tr>
 * <tr><td>local</td><td>basic</td><td>integral</td><td>20020523T140427-0500</td></tr>
 * <tr><td>UTC</td><td>basic</td><td>integral</td><td>20020523190427Z</td></tr>
 * <tr><td>local</td><td>extd.</td><td>integral</td><td>2002-05-23T14:04:27-05:00</td></tr>
 * <tr><td>UTC</td><td>extd.</td><td>integral</td><td>2002-05-23T19:04:27Z</td></tr>
 * <tr><td>local</td><td>basic</td><td>millis</td><td>20020523T140427.166-0500</td></tr>
 * <tr><td>UTC</td><td>basic</td><td>millis</td><td>20020523190427.166Z</td></tr>
 * <tr><td>local</td><td>extd.</td><td>millis</td><td>2002-05-23T14:04:27.166-05:00</td></tr>
 * <tr><td>UTC</td><td>extd.</td><td>millis</td><td>2002-05-23T19:04:27.166Z</td></tr>
 * </table><p>
 *
 * @param zuluTime returns a UTC formatted stamp, if true. Otherwise
 * the time will be formatted according to the local zone. Local time
 * should be prefixed with the 'T'.
 * @param extendedFormat will use the extended ISO 8601 format which
 * separates the different timestamp items. If false, the basic
 * format will be used. In UTC and basic format, the 'T' separator
 * will be omitted.
 * @param withMillis will put the millisecond extension into the timestamp.
 * If false, the time will be without millisecond fraction. The separator
 * is taken from {@link java.text.DecimalFormatSymbols#getMinusSign()},
 * which usually is a period or a comma.
 * @param now is a time stamp as Date.
 * @return an ISO 8601 formatted date and time representation for
 * the given point in time.
 */
public static String iso8601(boolean zuluTime, boolean extendedFormat, boolean withMillis, Date now) {
    Calendar c = Calendar.getInstance(zuluTime ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault());
    c.setTime(now);

    // set up formattting options
    DecimalFormat nf2 = new DecimalFormat("##00");
    DecimalFormat nf3 = new DecimalFormat("###000");
    DecimalFormat nf4 = new DecimalFormat("####0000");
    DecimalFormatSymbols dfs = nf2.getDecimalFormatSymbols();

    // allocate result string buffer
    int size = extendedFormat ? (zuluTime ? 25 : 30) : (zuluTime ? 21 : 25);
    if (!withMillis) {
        size -= 4;
    }
    StringBuffer result = new StringBuffer(size);

    result.append(nf4.format(c.get(Calendar.YEAR)));
    if (extendedFormat) {
        result.append('-'); // position 5
    }
    result.append(nf2.format(c.get(Calendar.MONTH) + 1));
    if (extendedFormat) {
        result.append('-'); // position 8
    }
    result.append(nf2.format(c.get(Calendar.DAY_OF_MONTH)));
    // generating UTC in basic format may leave out the 'T' separator
    if (extendedFormat || !zuluTime) {
        result.append('T'); // position 11
    }
    result.append(nf2.format(c.get(Calendar.HOUR_OF_DAY)));
    if (extendedFormat) {
        result.append(':'); // position 14
    }
    result.append(nf2.format(c.get(Calendar.MINUTE)));
    if (extendedFormat) {
        result.append(':'); // position 17
    }
    result.append(nf2.format(c.get(Calendar.SECOND)));

    if (withMillis) {
        // Though there is no explicit spec which allows a complete
        // timestamp with milliseconds, it is implied through two
        // levels, sigh. 5.3.4.2 allows decimal fractions with
        // time-only stamps that have a timezone. The intro of 5.4.2
        // allows 5.3.1.3.
        result.append(dfs.getDecimalSeparator()); // position 20
        result.append(nf3.format(c.get(Calendar.MILLISECOND)));
    }

    if (zuluTime) {
        // this is easy
        result.append('Z');
    } else {
        // time zone calculations
        int zone_offset = c.get(Calendar.ZONE_OFFSET) / 1000;
        int save_offset = c.get(Calendar.DST_OFFSET) / 1000;
        int diff = (zone_offset + save_offset) / 60;
        result.append(diff < 0 ? dfs.getMinusSign() : '+'); // position 24

        if (diff < 0) {
            diff = Math.abs(diff);
        }
        result.append(nf2.format(diff / 60));
        if (extendedFormat) {
            result.append(':');
        }
        result.append(nf2.format(diff % 60));
    }

    return result.toString();
}

From source file:org.opencastproject.capture.impl.ConfigurationManager.java

/**
 * Retrieve property for configuration. The return value for this function do *not* have its variable(s) expanded.
 * /*  w w  w .j  av  a 2 s  .c om*/
 * @param key
 *          the key to retrieve from the property list.
 * @return the value corresponding to the key.
 */
public String getUninterpretedItem(String key) {
    if (key == null) {
        return null;
    } else if (StringUtils.equals(key, "capture.device.timezone.offset")) {
        Calendar cal = Calendar.getInstance();
        return Long.toString((cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET))
                / (1 * CaptureParameters.MINUTES * CaptureParameters.MILLISECONDS));
    } else if (StringUtils.equals(key, "capture.device.timezone")) {
        return TimeZone.getDefault().getID();
    } else {
        return properties.getUninterpretedProperty(key);
    }
}

From source file:org.openbravo.service.json.JsonToDataConverter.java

private static Date convertToLocalTime(Date UTCTime) {
    Calendar localTime = Calendar.getInstance();
    localTime.setTime(UTCTime);/* www  .java 2 s .c  o m*/

    int gmtMillisecondOffset = (localTime.get(Calendar.ZONE_OFFSET) + localTime.get(Calendar.DST_OFFSET));
    localTime.add(Calendar.MILLISECOND, gmtMillisecondOffset);

    return localTime.getTime();
}