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:com.indoqa.lang.util.TimeUtilsTest.java

@Test
public void formatDate() {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT+1"));
    calendar.set(2012, 2, 1, 10, 5, 30);
    calendar.set(Calendar.MILLISECOND, 501);

    assertEquals("2012-03-01 09:05:30.501", TimeUtils.formatDate(calendar.getTime()));
}

From source file:com.indoqa.lang.util.TimeUtilsTest.java

@Test
public void parseDate() {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT+1"));
    calendar.set(2012, 2, 1, 10, 5, 30);
    calendar.set(Calendar.MILLISECOND, 501);

    assertEquals(calendar.getTimeInMillis(), TimeUtils.parseDate("2012-03-01 09:05:30.501").getTime());
}

From source file:ca.rmen.android.poetassistant.wotd.WotdLoader.java

@Override
public ResultListData<WotdEntry> loadInBackground() {
    Log.d(TAG, "loadInBackground()");

    List<WotdEntry> data = new ArrayList<>(100);

    Cursor cursor = mDictionary.getRandomWordCursor();
    if (cursor == null || cursor.getCount() == 0)
        return emptyResult();

    try {/*w  w  w.  j a v a2  s  .  com*/
        Set<String> favorites = mFavorites.getFavorites();
        Calendar calendar = Wotd.getTodayUTC();
        Calendar calendarDisplay = Wotd.getTodayUTC();
        calendarDisplay.setTimeZone(TimeZone.getDefault());
        Settings.Layout layout = Settings.getLayout(mPrefs);
        for (int i = 0; i < 100; i++) {
            Random random = new Random();
            random.setSeed(calendar.getTimeInMillis());
            String date = DateUtils.formatDateTime(getContext(), calendarDisplay.getTimeInMillis(),
                    DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            int position = random.nextInt(cursor.getCount());
            if (cursor.moveToPosition(position)) {
                String word = cursor.getString(0);
                @ColorRes
                int color = (i % 2 == 0) ? R.color.row_background_color_even : R.color.row_background_color_odd;
                data.add(new WotdEntry(word, date, ContextCompat.getColor(getContext(), color),
                        favorites.contains(word), layout == Settings.Layout.EFFICIENT));
            }
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            calendarDisplay.add(Calendar.DAY_OF_YEAR, -1);

        }

    } finally {
        cursor.close();
    }
    return new ResultListData<>(getContext().getString(R.string.wotd_list_header), false, data);
}

From source file:ch.algotrader.adapter.dc.DCFixMarketDataMessageHandler.java

public void onMessage(MarketDataSnapshotFullRefresh marketData, SessionID sessionID) throws FieldNotFound {

    Symbol symbol = marketData.getSymbol();

    int count = marketData.getGroupCount(NoMDEntries.FIELD);
    for (int i = 1; i <= count; i++) {

        Group group = marketData.getGroup(i, NoMDEntries.FIELD);
        char entryType = group.getChar(MDEntryType.FIELD);
        if (entryType == MDEntryType.BID || entryType == MDEntryType.OFFER) {

            double price = group.getDouble(MDEntryPx.FIELD);
            double size = group.getDouble(MDEntrySize.FIELD);
            Date time = group.getUtcTimeOnly(MDEntryTime.FIELD);

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
            calendar = DateUtils.truncate(calendar, Calendar.DATE);
            Date date = new Date(calendar.getTimeInMillis() + time.getTime());

            String tickerId = symbol.getValue();
            switch (entryType) {
            case MDEntryType.BID:

                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("{} BID {}@{}", symbol.getValue(), size, price);
                }//www .j  ava2s.c  o m

                BidVO bidVO = new BidVO(tickerId, FeedType.DC.name(), date, price, (int) size);
                this.serverEngine.sendEvent(bidVO);
                break;
            case MDEntryType.OFFER:

                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("{} ASK {}@{}", symbol.getValue(), size, price);
                }

                AskVO askVO = new AskVO(tickerId, FeedType.DC.name(), date, price, (int) size);

                this.serverEngine.sendEvent(askVO);
                break;
            }
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitExpiresHandler.java

@Override
public void parse(final SetCookie cookie, String value) throws MalformedCookieException {
    if (value.startsWith("\"") && value.endsWith("\"")) {
        value = value.substring(1, value.length() - 1);
    }//from w  w  w  .  j  a  v  a 2s. co  m
    value = value.replaceAll("[ ,:-]+", " ");

    Date startDate = null;
    String[] datePatterns = DEFAULT_DATE_PATTERNS;

    if (null != browserVersion_) {
        if (browserVersion_.hasFeature(HTTP_COOKIE_START_DATE_1970)) {
            startDate = HtmlUnitBrowserCompatCookieSpec.DATE_1_1_1970;
        }

        if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_1)) {
            datePatterns = EXTENDED_DATE_PATTERNS_1;
        }

        if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_2)) {
            final Calendar calendar = Calendar.getInstance(Locale.ROOT);
            calendar.setTimeZone(DateUtils.GMT);
            calendar.set(1969, Calendar.JANUARY, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startDate = calendar.getTime();

            datePatterns = EXTENDED_DATE_PATTERNS_2;
        }
    }

    final Date expiry = DateUtils.parseDate(value, datePatterns, startDate);
    cookie.setExpiryDate(expiry);
}

From source file:ymanv.forex.provider.impl.EuropeanCentralBank.java

private List<RateEntity> getRates(String response, boolean usdBase) throws IOException {
    SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT_STRNG);
    Calendar sfCalendar = sf.getCalendar();
    sfCalendar.setTimeZone(TZ);

    List<RateEntity> rates = new ArrayList<>();

    String cleanResponse = response.substring(response.indexOf("<Cube>"), response.lastIndexOf("</Cube>") + 7);
    try {/*from ww w.j a va 2  s . c  o m*/
        JAXBContext context = JAXBContext.newInstance(Result.class);
        Unmarshaller un = context.createUnmarshaller();
        Result res = (Result) un.unmarshal(new StringReader(cleanResponse));

        for (Day d : res.getDays()) {
            Date date = d.getDate();
            sf.parse(sf.format(date));
            sfCalendar.set(Calendar.HOUR, 15);
            date = sf.getCalendar().getTime();

            if (!usdBase) {
                for (Rate r : d.getRates()) {
                    rates.add(new RateEntity(BASE_CURRENCY, r.getTocur(), new BigDecimal(r.getValue()), date));
                }
            } else {
                BigDecimal usdToEurValue = null;

                for (Rate r : d.getRates()) {
                    if (USD.equals(r.getTocur())) {
                        usdToEurValue = invert(new BigDecimal(r.getValue()));
                        break;
                    }
                }

                for (Rate r : d.getRates()) {
                    if (USD.equals(r.getTocur())) {
                        rates.add(new RateEntity(USD, BASE_CURRENCY, usdToEurValue, date));
                    } else {
                        rates.add(new RateEntity(USD, r.getTocur(),
                                new BigDecimal(r.getValue()).multiply(usdToEurValue), date));
                    }
                }
            }
        }

        return rates;
    } catch (ParseException | JAXBException e) {
        throw new IOException(e);
    }
}

From source file:org.ow2.proactive.scheduler.policy.edf.JobMostLikelyMissedEmailNotification.java

private String getBody() throws IOException {
    final ClassLoader classLoader = JobMostLikelyMissedEmailNotification.class.getClassLoader();
    if (jobExecutionTime != null) {
        final String template = IOUtils.toString(
                Objects.requireNonNull(
                        classLoader.getResource("email-templates/most-likely-missed-with-duration.template")),
                Charset.defaultCharset());

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
        calendar.setTimeInMillis(0);//from w w w . j av a 2s  . c om
        calendar.add(Calendar.SECOND, (int) jobExecutionTime.getSeconds());
        final String strJobExecutionTime = jobExecutionTimeFormat.format(calendar.getTime());

        return String.format(template, internalJob.getId().value(), deadline, strJobExecutionTime,
                finishingTime);
    } else {
        final String template = IOUtils.toString(
                Objects.requireNonNull(classLoader
                        .getResource("email-templates/most-likely-missed-without-duration.template")),
                Charset.defaultCharset());

        return String.format(template, internalJob.getId().value(), deadline, finishingTime);
    }
}

From source file:com.persistent.cloudninja.controller.RunningInstancesJSONDataController.java

public List<String> generateStartAndEndTime(int year, int month) {
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.sss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date currentDate = cal.getTime();
    int currentMonth = cal.get(Calendar.MONTH) + 1;

    String start = month + "/01/" + year + " 00:00:00.000";
    String end = null;/*from www. j  av  a2s  .  c om*/

    if (month == currentMonth) {
        end = dateFormat.format(currentDate);
    } else {
        try {
            cal.setTime(dateFormat.parse(start));
            int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            end = month + "/" + maxDay + "/" + year + " 23:59:59.000";

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
    List<String> time = new ArrayList<String>();
    time.add(start);
    time.add(end);
    return time;
}

From source file:io.wcm.devops.conga.plugins.aem.util.JsonContentLoaderTest.java

@Test
public void testCalendarEcmaFormat() {
    Map<String, Object> props = getDeep(content, "jcr:content");

    Calendar calendar = (Calendar) props.get("cq:lastModified");
    assertNotNull(calendar);//w  w w  .j a v  a2s  .  c  o m

    calendar.setTimeZone(TimeZone.getTimeZone("GMT+2"));

    assertEquals(2014, calendar.get(Calendar.YEAR));
    assertEquals(4, calendar.get(Calendar.MONTH) + 1);
    assertEquals(22, calendar.get(Calendar.DAY_OF_MONTH));

    assertEquals(15, calendar.get(Calendar.HOUR_OF_DAY));
    assertEquals(11, calendar.get(Calendar.MINUTE));
    assertEquals(24, calendar.get(Calendar.SECOND));
}

From source file:com.boozallen.cognition.ingest.storm.bolt.logging.LogRecordDateBoltTest.java

@Test
public void testLogDate(@Injectable LogRecord record, @Injectable Logger logger) throws Exception {
    bolt.logger = logger;//from  w w w .j a  v a 2 s  .  c o m
    bolt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
    bolt.level = Level.DEBUG;

    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    calendar.set(2014, Calendar.JUNE, 10, 20, 22, 4);

    new Expectations(bolt) {
        {
            record.getDate();
            result = calendar.getTime();
            bolt.log(logger, "2014-06-10T20:22:04.000Z");
        }
    };
    bolt.logDate(record);
}