Example usage for java.util Calendar getTimeZone

List of usage examples for java.util Calendar getTimeZone

Introduction

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

Prototype

public TimeZone getTimeZone() 

Source Link

Document

Gets the time zone.

Usage

From source file:org.jasig.portlet.cms.model.repository.schedule.ScheduledPostPublisher.java

private void publishScheduledPostsForRepositoryRoot(final String root) throws JcrRepositoryException {
    final Collection<Post> scheduledPosts = getRepositoryDao().getScheduledPosts(root);

    if (scheduledPosts != null && scheduledPosts.size() > 0)
        for (final Post post : scheduledPosts) {

            final Calendar cldr = Calendar.getInstance(post.getLocale());
            final DateTimeFormatter fmt = DateTimeFormat
                    .forPattern(PortletPreferencesWrapper.DEFAULT_POST_DATE_FORMAT);

            final DateTime dt = DateTime.parse(post.getScheduledDate(), fmt);

            final DateTimeZone zone = DateTimeZone.forTimeZone(cldr.getTimeZone());
            final DateTime today = new DateTime(zone);

            if (dt.isEqual(today) || dt.isBefore(today)) {
                if (logger.isDebugEnabled())
                    logger.debug("Scheduled for today " + post.getPath() + " at " + post.getScheduledDate());

                getRepositoryDao().removePost(post.getPath());
                post.setPath(root);//from w  ww .j  a  v  a  2  s . com
                post.setRateCount(0);
                post.setRate(0);
                getRepositoryDao().setPost(post);

                if (logger.isDebugEnabled())
                    logger.debug("Published scheduled post " + post.getPath() + " at " + post.getScheduledDate()
                            + " to " + post.getPath());
            }
        }
    else
        ScheduledPostsManager.getInstance().removeRepositoryRoot(root);
}

From source file:org.jasig.schedassist.web.owner.schedule.BlockBuilderFormBackingObjectValidator.java

private long approximateMinutesDifference(Matcher startTimeMatcher, Matcher endTimeMatcher) {
    Date now = new Date();

    Calendar s = Calendar.getInstance();
    s.setTime(now);/*  ww w.  ja va  2  s  . c o m*/

    s.set(Calendar.HOUR_OF_DAY, convertHourOfDay(startTimeMatcher));
    s.set(Calendar.MINUTE, Integer.parseInt(startTimeMatcher.group(2)));

    Calendar e = Calendar.getInstance();
    e.setTime(now);

    e.set(Calendar.HOUR_OF_DAY, convertHourOfDay(endTimeMatcher));
    e.set(Calendar.MINUTE, Integer.parseInt(endTimeMatcher.group(2)));

    long endL = e.getTimeInMillis() + e.getTimeZone().getOffset(e.getTimeInMillis());
    long startL = s.getTimeInMillis() + s.getTimeZone().getOffset(s.getTimeInMillis());

    return (endL - startL) / MILLISECS_PER_MIN;
}

From source file:es.sonxurxo.android.androidroulette.client.HttpHelper.java

public PoolResponse send(String message, long lastReadMessage) throws EndedException, Exception {

    HttpConnectionParams.setConnectionTimeout(client.getParams(), HttpHelper.TIMEOUT);
    HttpConnectionParams.setSoTimeout(client.getParams(), HttpHelper.TIMEOUT);

    this.request = new HttpPost(this.FULL_ADDRESS + this.SEND_URL + "?" + this.PARAMETER_NAME_LAST_READ_MESSAGE
            + "=" + String.valueOf(lastReadMessage) + "&" + this.PARAMETER_NAME_MESSAGE + "="
            + URLEncoder.encode(String.valueOf(message), "UTF-8"));

    try {/*from w w w . java2s. c  o  m*/
        this.response = client.execute(this.request);
        PoolResponse result = new PoolResponse();
        String s = this.convertStreamToString(this.response.getEntity().getContent());
        JSONObject object = new JSONObject(s);
        if (object.has(this.JSON_MESSAGE) && object.getString(this.JSON_MESSAGE).equals(this.JSON_ENDED)) {
            throw new EndedException();
        }
        if (object.has(this.JSON_MATE_TYPING)) {
            result.setMateTyping(object.getBoolean(this.JSON_MATE_TYPING));
        }
        SimpleDateFormat sdf = new SimpleDateFormat(HttpHelper.DATE_FORMAT, Locale.US);

        String myDate = object.getString(this.JSON_MY_DATE);
        Calendar myDateCalendar = Calendar.getInstance();
        myDateCalendar.setTime(sdf.parse(myDate));
        myDateCalendar.add(Calendar.MILLISECOND, myDateCalendar.getTimeZone().getRawOffset());

        List<Message> messsagesList = new ArrayList<Message>();

        if (new JSONObject(s).has(this.JSON_MESSAGES)) {
            JSONArray array = new JSONObject(s).getJSONArray(this.JSON_MESSAGES);

            for (int i = 0; i < array.length(); i++) {
                JSONObject messageObject = array.getJSONObject(i);
                Calendar date = Calendar.getInstance();
                date.setTime(sdf.parse(messageObject.getString(this.JSON_DATE)));
                date.add(Calendar.MILLISECOND, date.getTimeZone().getRawOffset());
                messsagesList.add(new Message(messageObject.getString(this.JSON_TEXT), date));
            }
        }
        messsagesList.add(new Message(null, myDateCalendar));
        result.setMessages(messsagesList);
        return result;
    } catch (ConnectTimeoutException e) {
        throw e;
    } catch (EndedException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.codekaizen.vtj.text.BpDateFormatTest.java

/**
 * DOCUMENT ME!/*www .j a  va  2 s .com*/
 */
public void testIsoFormatting() {
    BpDateFormat fmt1 = null;
    String str1 = null;
    Calendar cal = Calendar.getInstance();

    if (!cal.getTimeZone().getID().equals("America/Chicago")) {
        cal.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
        cal.clear();
    }

    cal.set(2002, Calendar.JANUARY, 2, 8, 16, 44);
    cal.set(Calendar.MILLISECOND, 18);

    fmt1 = new BpDateFormat(BpDateFormat.ISO_DATE_ONLY, Locale.US);
    str1 = fmt1.format(cal.getTime());
    assertEquals("2002-01-02", str1);

    fmt1 = new BpDateFormat(BpDateFormat.ISO_YEAR_WEEK, Locale.US);
    str1 = fmt1.format(cal.getTime());
    assertEquals("2002-W01", str1);

    fmt1 = new BpDateFormat(BpDateFormat.ISO_TIME_ONLY, Locale.US);
    str1 = fmt1.format(cal.getTime());
    assertEquals("T08:16:44", str1);

    fmt1 = new BpDateFormat(BpDateFormat.ISO_DATE_TIME, Locale.US);
    str1 = fmt1.format(cal.getTime());
    assertEquals("2002-01-02T08:16:44.018-06:00", str1);

    cal.set(Calendar.MONTH, Calendar.JUNE);
    str1 = fmt1.format(cal.getTime());
    assertEquals("2002-06-02T08:16:44.018-05:00", str1);

    cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    cal.set(2002, Calendar.JANUARY, 2, 8, 16, 44);
    cal.set(Calendar.MILLISECOND, 18);
    fmt1.setTimeZone(TimeZone.getTimeZone("UTC"));
    str1 = fmt1.format(cal.getTime());
    assertEquals("2002-01-02T08:16:44.018Z", str1);

    cal.set(Calendar.MONTH, Calendar.JUNE);
    str1 = fmt1.format(cal.getTime());
    assertEquals("2002-06-02T08:16:44.018Z", str1);

    cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tehran"));
    cal.set(2002, Calendar.JANUARY, 2, 8, 16, 44);
    cal.set(Calendar.MILLISECOND, 18);
    fmt1.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
    str1 = fmt1.format(cal.getTime());
    assertEquals("2002-01-02T08:16:44.018+03:30", str1);

}

From source file:es.sonxurxo.android.androidroulette.client.HttpHelper.java

public PoolResponse pool(long lastReadMessage, boolean typing) throws EndedException, Exception {

    HttpConnectionParams.setConnectionTimeout(client.getParams(), HttpHelper.TIMEOUT);
    HttpConnectionParams.setSoTimeout(client.getParams(), HttpHelper.TIMEOUT);

    this.request = new HttpPost(this.FULL_ADDRESS + this.POOL_URL + "?" + this.PARAMETER_NAME_LAST_READ_MESSAGE
            + "=" + String.valueOf(lastReadMessage) + "&" + this.PARAMETER_NAME_TYPING + "="
            + String.valueOf(typing));

    try {/*  w w  w  .  ja va  2s.c om*/
        this.response = client.execute(this.request);
        PoolResponse result = new PoolResponse();
        String s = this.convertStreamToString(this.response.getEntity().getContent());
        JSONObject object = new JSONObject(s);
        if (object.has(this.JSON_MESSAGE) && object.getString(this.JSON_MESSAGE).equals(this.JSON_ENDED)) {
            throw new EndedException();
        }
        if (object.has(this.JSON_MATE_TYPING)) {
            result.setMateTyping(object.getBoolean(this.JSON_MATE_TYPING));
        }
        if (object.has(this.JSON_MESSAGE)
                && object.getString(this.JSON_MESSAGE).equals(this.JSON_NO_MESSAGES)) {
            return result;
        }

        JSONArray array = new JSONObject(s).getJSONArray(this.JSON_MESSAGES);
        List<Message> messagesList = new ArrayList<Message>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject messageObject = array.getJSONObject(i);
            SimpleDateFormat sdf = new SimpleDateFormat(HttpHelper.DATE_FORMAT, Locale.US);
            Calendar date = Calendar.getInstance();

            date.setTime(sdf.parse(messageObject.getString(this.JSON_DATE)));
            date.add(Calendar.MILLISECOND, date.getTimeZone().getRawOffset());

            messagesList.add(new Message(messageObject.getString(this.JSON_TEXT), date));
        }
        result.setMessages(messagesList);
        return result;
    } catch (ConnectTimeoutException e) {
        throw e;
    } catch (EndedException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }
}

From source file:helper.lang.DateHelperTest.java

@Test
public void testNowUtc() {
    long nowBeforeCall = System.currentTimeMillis();
    Calendar cal = DateHelper.nowUtc();
    long nowAfterCall = System.currentTimeMillis();
    assertTrue(cal.getTimeInMillis() >= nowBeforeCall);
    assertTrue(cal.getTimeInMillis() <= nowAfterCall);
    assertEquals(DateHelper.UTC_TIME_ZONE, cal.getTimeZone());
}

From source file:com.taobao.tdhs.jdbc.TDHSPreparedStatement.java

private DateFormat getDateFormat(Calendar cal) {
    DateFormat dateFormat = (DateFormat) DEFAULT_DATE_FORMAT.clone();
    if (cal != null) {
        TimeZone timeZone = cal.getTimeZone();
        dateFormat.setTimeZone(timeZone);
    }/*from  w w w . java 2  s .  c om*/
    return dateFormat;
}

From source file:com.rsltc.profiledata.main.MainActivity.java

private static void processDistanceSummary(DataSet dataSet, InfoType type, DistanceSummary summary) {
    Calendar calendar = Calendar.getInstance();
    for (DataPoint dp : dataSet.getDataPoints()) {
        Float distance = null;/*from   w w w.java  2s . c om*/
        Log.i(TAG, "Data point:");
        Log.i(TAG, "\tType: " + dp.getDataType().getName());
        Long startTime = dp.getStartTime(TimeUnit.MILLISECONDS);
        calendar.setTimeInMillis(startTime);
        Log.i(TAG, "\tStart: " + calendar.getTime());
        Long stopTime = dp.getEndTime(TimeUnit.MILLISECONDS);
        calendar.setTimeInMillis(stopTime);
        Log.i(TAG, "\tStop: " + calendar.getTime());

        Long duration = stopTime - startTime;
        Log.i(TAG, "Timezone: " + calendar.getTimeZone().getDisplayName());
        for (Field field : dp.getDataType().getFields()) {
            Log.i(TAG, "\tField: " + field.getName() + " Value: " + dp.getValue(field));
            if (field.equals(Field.FIELD_DISTANCE)) {
                distance = dp.getValue(field).asFloat();
            } else {
                Log.e(TAG, "Unsupported field found");
            }
        }
        boolean valid = false;
        if (distance != null) {
            valid = HealthStatValidityChecker.checkIfNormalDistance(distance, type);
        }
        if (valid) {
            summary.setMaxDistanceIfGreater(distance);
            summary.setMinDistanceIfSmaller(distance);
            summary.setMaxDurationIfLonger(duration);
            summary.setMinDurationIfShorter(duration);
            double count = summary.getCount();
            summary.setAvgDistance((summary.getAvgDistance() * count + distance) / (count + 1));
            summary.setAvgDuration((float) ((summary.getAvgDuration() * count + duration) / (count + 1)));
            summary.increaseCount();
        }
    }
}

From source file:org.jasig.portlet.calendar.adapter.ExchangeCalendarAdapterTest.java

@Test
public void testGetInternalEvent() throws DatatypeConfigurationException {
    com.microsoft.exchange.types.CalendarEvent msEvent = new com.microsoft.exchange.types.CalendarEvent();

    // set the test event start time to 4AM on November 1, 2010
    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    XMLGregorianCalendar start = datatypeFactory.newXMLGregorianCalendar();
    start.setYear(2010);//ww w.ja  v a  2 s  . co m
    start.setMonth(11);
    start.setDay(1);
    start.setTime(4, 0, 0, 0);
    msEvent.setStartTime(start);

    // set the test event end time to 5AM on November 1, 2010
    XMLGregorianCalendar end = datatypeFactory.newXMLGregorianCalendar();
    end.setYear(2010);
    end.setMonth(12);
    end.setDay(1);
    end.setTime(5, 0, 0, 0);
    msEvent.setEndTime(end);

    // set the event tname and location
    CalendarEventDetails details = new CalendarEventDetails();
    details.setSubject("Naptime");
    details.setLocation("My house");
    msEvent.setCalendarEventDetails(details);

    // transform the Microsoft calendar event into a calendar portlet event
    VEvent event = adapter.getInternalEvent(3, msEvent);

    // ensure the calendar id, summary, and location are all set correctly
    assertEquals("Naptime", event.getSummary().getValue());
    assertEquals("My house", event.getLocation().getValue());

    // check the start time
    Calendar cal = Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(event.getStartDate().getDate().getTime());
    assertEquals(4, cal.get(Calendar.HOUR_OF_DAY));
    assertEquals(java.util.TimeZone.getTimeZone("UTC"), cal.getTimeZone());
    assertTrue(event.getStartDate().isUtc());
    assertNull(event.getStartDate().getTimeZone());

    // check the end time
    cal.setTimeInMillis(event.getEndDate().getDate().getTime());
    assertEquals(5, cal.get(Calendar.HOUR_OF_DAY));
    assertEquals(java.util.TimeZone.getTimeZone("UTC"), cal.getTimeZone());
    assertTrue(event.getEndDate().isUtc());
    assertNull(event.getEndDate().getTimeZone());

}

From source file:helper.lang.DateHelperTest.java

@Test
public void testAsUtcDayCalendar() {
    Calendar localTime = Calendar.getInstance(TimeZone.getTimeZone("CST"));
    Calendar cal = DateHelper.asUtcDay(localTime);
    assertEquals(0, cal.get(Calendar.MILLISECOND));
    assertEquals(0, cal.get(Calendar.MINUTE));
    assertEquals(0, cal.get(Calendar.HOUR));
    assertEquals(0, cal.get(Calendar.HOUR_OF_DAY));
    assertEquals(DateHelper.UTC_TIME_ZONE, cal.getTimeZone());
    assertEquals(TimeZone.getTimeZone("CST"), localTime.getTimeZone());
    assertEquals(localTime.get(Calendar.YEAR), cal.get(Calendar.YEAR));
    assertEquals(localTime.get(Calendar.MONTH), cal.get(Calendar.MONTH));
    assertEquals(localTime.get(Calendar.DATE), cal.get(Calendar.DATE));
}