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.citrix.g2w.webdriver.pages.BasePage.java

/**
 * Method used to convert date time text to desired date time text along
 * with specified time zone./*from  www . ja  va 2 s . c  o m*/
 * <ol>
 * <li>Input Format: Fri, Jan 10, 2014 9:00 PM - 10:00 PM PST</li>
 * <li>Input Format : Thu, Jan 9, 2014 11:00 PM - Fri, Jan 10, 2014 12:00 AM
 * PST</li>
 * <li>Input Time Zone Format: US/Pacific (for pacific region)</li>
 * <li>Output Format: Friday, January 10, 2014 12:00 AM - 1:00 AM PST</li>
 * <li>Output Format: Thursday, January 9, 2014 11:00 PM - Friday, January
 * 10, 2014 12:00 AM PST</li>
 * </ol>
 *
 * @param dateTimeText
 *            (date and time in text format)
 * @param toTimeZone
 *            (conversion time zone id)
 * @return expectedDateTimeText
 */
public String computeWebinarDurationInTimeZone(final String dateTimeText, final String toTimeZone) {

    Calendar c = Calendar.getInstance();
    c.setTimeZone(TimeZone.getTimeZone(toTimeZone));
    int timeZonePosition = dateTimeText.lastIndexOf(" ");
    String timeZoneText = dateTimeText.substring(timeZonePosition + 1);
    String[] dateArray = dateTimeText.split("-");
    String startDateTimeText = this.convertDateTextBasedOnPattern(
            this.messages.getMessage("date.format.registrant.start.long", null, this.locale),
            dateArray[0].trim() + " " + timeZoneText.trim(), toTimeZone);
    String endDateTimeText = "";
    if (dateArray[1].length() <= 13) {
        endDateTimeText = this.convertDateTextBasedOnPattern(
                this.messages.getMessage("date.format.registrant.start.short", null, this.locale),
                startDateTimeText, toTimeZone);
        endDateTimeText = endDateTimeText + " " + dateArray[1].trim();
    } else {
        endDateTimeText = dateArray[1].trim();
    }
    Date startDate = this.convertDateTextToObject(
            this.messages.getMessage("date.format.registrant.start.long", null, this.locale), startDateTimeText,
            toTimeZone);
    c.setTime(startDate);
    String startDayOfMonth = this.convertDateObjectToText(
            this.messages.getMessage("date.format.registrant.start.long.formatted", null, this.locale),
            c.getTime(), toTimeZone);
    Date endDate = this.convertDateTextToObject(
            this.messages.getMessage("date.format.registrant.start.long", null, this.locale), endDateTimeText,
            toTimeZone);
    String endDayOfMonth = "";
    if (startDate.after(endDate)) {
        c.setTime(endDate);
        c.add(Calendar.DAY_OF_MONTH, 1);
        endDayOfMonth = this.convertDateObjectToText(
                this.messages.getMessage("date.format.registrant.start.long.formatted", null, this.locale),
                c.getTime(), toTimeZone);
    } else {
        c.setTime(endDate);
        endDayOfMonth = this.convertDateObjectToText(
                this.messages.getMessage("date.format.registrant.start.long.formatted", null, this.locale),
                c.getTime(), toTimeZone);
    }
    String formattedStartDate = this.convertDateObjectToText(
            this.messages.getMessage("date.format.registrant.start.long", null, this.locale), startDate,
            toTimeZone);
    String formattedEndDate = "";
    if ((Integer.parseInt(startDayOfMonth) != Integer.parseInt(endDayOfMonth))) {
        formattedEndDate = this.convertDateObjectToText(
                this.messages.getMessage("date.format.registrant.end.diffDay", null, this.locale), endDate,
                toTimeZone);
    } else {
        formattedEndDate = this.convertDateObjectToText(
                this.messages.getMessage("date.format.registrant.end.sameDay", null, this.locale), endDate,
                toTimeZone);
    }

    // Get the expected date and time in string format.
    String expectedDateTimeText = formattedStartDate.substring(0, formattedStartDate.lastIndexOf(" ")).trim()
            + " - " + formattedEndDate;
    return expectedDateTimeText;
}

From source file:org.springframework.data.solr.core.DefaultQueryParserTests.java

@Test
public void testIsWithJavaDateValue() {
    DateTime dateTime = new DateTime(2012, 8, 21, 6, 35, 0, DateTimeZone.UTC);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    calendar.setTimeInMillis(dateTime.getMillis());

    Criteria criteria = new Criteria("dateField").is(calendar.getTime());
    Assert.assertEquals("dateField:2012\\-08\\-21T06\\:35\\:00.000Z",
            queryParser.createQueryStringFromCriteria(criteria));
}

From source file:org.apache.jena.graph.test.TestTypedLiterals.java

/**
 * Test ability to override an apparent DateTime to be just a date
 *///w  w w  .  j a  v a 2  s .  c  om
public void testDateOverride() {
    Calendar date = new GregorianCalendar(2007, 3, 4);
    date.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    XSDDateTime xsdDate = new XSDDateTime(date);
    Literal l1 = m.createTypedLiteral(xsdDate, XSDDatatype.XSDdate);

    assertEquals(XSDDatatype.XSDdate, l1.getDatatype());
    assertEquals("2007-04-04Z", l1.getLexicalForm());
}

From source file:org.apache.jena.graph.test.TestTypedLiterals.java

public void testDateTimeBug2() throws Exception {
    String[] timezonelist = { "GMT", "America/New_York", "America/Chicago", };

    for (String timezoneid : timezonelist) {
        TimeZone tz = TimeZone.getTimeZone(timezoneid);
        String[] sampletimelist = { "03/10/2012 01:29",
                // 03/11/2012 DST time change at 2 am
                "03/11/2012 00:29", "03/11/2012 01:29", "03/11/2012 02:29", "03/11/2012 03:29",
                "03/11/2012 04:29",

                "03/12/2012 01:29", "11/03/2012 23:29",
                // 11/04/2012 standard time change at 2 am
                "11/04/2012 00:29", "11/04/2012 01:29", "11/04/2012 02:29", "11/04/2012 03:29", };

        String format = "MM/dd/yyy HH:mm";
        for (String tstr : sampletimelist) {
            Date dt = getDateFromPattern(tstr, format, timezoneid);
            SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
            df.setTimeZone(tz);// w  w w .j  a v a  2 s  .c  o m
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(tz);
            cal.setTime(dt);
            XSDDateTime xdt = new XSDDateTime(cal);
            int offset = tz.getOffset(dt.getTime()) / (60 * 60 * 1000);
            int xhr = xdt.getHours();
            int dhr = cal.get(Calendar.HOUR_OF_DAY);
            int dif = (xhr - dhr + offset) % 24;
            Assert.assertEquals("Difference between cal and xdt", 0, dif);

            //                //System.out.println("xhr="+xhr+",dhr="+dhr+",dif="+dif);
            //                System.out.println(""
            //                    +"tstr="+tstr
            //                    +"\tdate="+df.format(dt)
            //                    +(dif==0?"\t ":"\tX")
            //                    +" xsddt="+xdt
            //                    +"\toffset="+offset);
        }
        //System.out.println();
    }
}

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

/**
 * Test the conversion of java.util.Calendar objects in the Anzo.java API into xsd:dateTime RDF literals with time zones. The test will add statements using
 * java.util.Calendar objects and verify that when those statements are retrieved, the expected lexical value, datatype, etc. are correct.
 * /*from  ww w.  j a  va 2 s .c  o  m*/
 * @throws Exception
 */
public void testCalendarBecomesXsdDateTime() throws Exception {

    AnzoClient client = null;
    try {
        client = new AnzoClient(getDefaultClientConfiguration());
        client.connect();
        client.reset(loadStatements("initialize.trig"), null);
        ClientGraph graph = client.getReplicaGraph(GRAPH_URI);

        DatatypeFactory df = DatatypeFactory.newInstance();

        // UTC
        Calendar cal = getCleanCalendar();
        cal.set(2008, Calendar.JULY, 11, 16, 48, 32);
        XMLGregorianCalendar xmlcal = df.newXMLGregorianCalendar(2008, DatatypeConstants.JULY, 11, 16, 48, 32,
                DatatypeConstants.FIELD_UNDEFINED, 0);
        addAndRetrieveNativeLiteral(client, graph, cal, xmlcal, "2008-07-11T16:48:32Z", XMLSchema.DATETIME);

        // Time zone offset
        cal = getCleanCalendar();
        cal.set(2008, Calendar.JULY, 11, 16, 48, 32);
        cal.setTimeZone(TimeZone.getTimeZone("GMT-09:00"));
        xmlcal = df.newXMLGregorianCalendar(2008, DatatypeConstants.JULY, 11, 16, 48, 32,
                DatatypeConstants.FIELD_UNDEFINED, -9 * 60);
        addAndRetrieveNativeLiteral(client, graph, cal, xmlcal, "2008-07-11T16:48:32-09:00",
                XMLSchema.DATETIME);

        // Fractional seconds
        cal = getCleanCalendar();
        cal.set(2008, Calendar.JULY, 11, 16, 48, 32);
        cal.set(Calendar.MILLISECOND, 357);
        cal.setTimeZone(TimeZone.getTimeZone("GMT-03:00"));
        xmlcal = df.newXMLGregorianCalendar(2008, DatatypeConstants.JULY, 11, 16, 48, 32, 357, -3 * 60);
        addAndRetrieveNativeLiteral(client, graph, cal, xmlcal, "2008-07-11T16:48:32.357-03:00",
                XMLSchema.DATETIME);

        // A partially filled Calendar still ends up as a fully specified xsd:dateTime with the default values
        // used for unspecified fields (i.e. 0 for time fields, January for month, 1 for day of month, etc.) 
        cal = getCleanCalendar();
        cal.set(2008, Calendar.JULY, 11);
        cal.setTimeZone(TimeZone.getTimeZone("GMT-03:00"));
        xmlcal = df.newXMLGregorianCalendar(2008, DatatypeConstants.JULY, 11, 0, 0, 0,
                DatatypeConstants.FIELD_UNDEFINED, -3 * 60);
        addAndRetrieveNativeLiteral(client, graph, cal, xmlcal, "2008-07-11T00:00:00-03:00",
                XMLSchema.DATETIME);

        // Another partially filled Calendar. 
        cal = getCleanCalendar();
        cal.set(Calendar.YEAR, 2012);
        xmlcal = df.newXMLGregorianCalendar(2012, DatatypeConstants.JANUARY, 1, 0, 0, 0,
                DatatypeConstants.FIELD_UNDEFINED, 0);
        addAndRetrieveNativeLiteral(client, graph, cal, xmlcal, "2012-01-01T00:00:00Z", XMLSchema.DATETIME);

    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:com.orange.oidc.tim.service.SIMStorage.java

public String save_tokens(OpenidConnectParams ocp, String id_token, String refresh_token, String expires_in,
        boolean sendReq) {

    if (ocp != null) {
        TokensKeys tokens_keys = new TokensKeys();
        tokens_keys.id_token = id_token;
        tokens_keys.refresh_token = refresh_token;
        int expires = 0;
        try {/*from ww w .  j  a  v  a  2  s  .com*/
            expires = Integer.parseInt(expires_in);
        } catch (Exception e) {
        }

        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        tokens_keys.timems = cal.getTimeInMillis() + 1000 * expires;
        tokens_keys.expires = "" + (tokens_keys.timems / 1000); // Long.toHexString(tokens_keys.timems);

        return save_app_req_tokens(ocp.m_server_url, ocp.m_client_id, ocp.m_scope, tokens_keys, sendReq);
    }
    return null;
}

From source file:com.citrix.g2w.webdriver.pages.BasePage.java

/**
 * Method used to convert string date format to date object.
 *
 * @param pattern/*from   w  w  w .j  a va2  s .  c o m*/
 *            (The pattern of the date time string parameter)
 * @param dateTimeString
 *            (Date and time format in String)
 * @param timeZone
 *            (time zone)
 * @return Date (date object)
 */
public Date convertDateTextToObject(final String pattern, final String dateTimeString, final String timeZone) {
    Date date = null;
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(pattern, this.locale);
    try {
        date = sdf.parse(dateTimeString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    c.setTimeZone(TimeZone.getTimeZone(timeZone));
    c.setTime(date);
    return c.getTime();
}

From source file:com.citrix.g2w.webdriver.pages.BasePage.java

/**
 * Method to convert date text based on pattern.
 *
 * @param pattern//w  w  w . ja v a  2 s  .c  o  m
 *            (The pattern of the date time parameter)
 * @param dateTimeString
 *            (Date and time format in String)
 * @param timeZone
 *            (time zone)
 * @return formatted date based on pattern
 */
public String convertDateTextBasedOnPattern(final String pattern, final String dateTimeString,
        final String timeZone) {
    Date date = null;
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(pattern, this.locale);
    try {
        date = sdf.parse(dateTimeString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    c.setTimeZone(TimeZone.getTimeZone(timeZone));
    c.setTime(date);
    return sdf.format(c.getTime());
}

From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java

private Map getWeblogEntryMap(Weblog website, Date startDate, Date endDate, String catName, List tags,
        String status, boolean stringsOnly, String locale, int offset, int length) throws WebloggerException {

    TreeMap map = new TreeMap(reverseComparator);

    List entries = getWeblogEntries(website, null, // user
            startDate, endDate, catName, tags, status, null, // text
            null, // sortBy
            null, // sortOrder
            locale, offset, length);/*  w ww.j a v  a2  s . co  m*/

    Calendar cal = Calendar.getInstance();
    if (website != null) {
        cal.setTimeZone(website.getTimeZoneInstance());
    }

    SimpleDateFormat formatter = DateUtil.get8charDateFormat();
    for (Iterator wbItr = entries.iterator(); wbItr.hasNext();) {
        WeblogEntry entry = (WeblogEntry) wbItr.next();
        Date sDate = DateUtil.getNoonOfDay(entry.getPubTime(), cal);
        if (stringsOnly) {
            if (map.get(sDate) == null)
                map.put(sDate, formatter.format(sDate));
        } else {
            List dayEntries = (List) map.get(sDate);
            if (dayEntries == null) {
                dayEntries = new ArrayList();
                map.put(sDate, dayEntries);
            }
            dayEntries.add(entry);
        }
    }
    return map;
}

From source file:com.wdullaer.materialdatetimepicker.date.DatePickerDialog.java

private void setToNearestDate(Calendar calendar) {
    if (!selectableDays.isEmpty()) {
        Calendar newCalendar = null;
        Calendar higher = selectableDays.ceiling(calendar);
        Calendar lower = selectableDays.lower(calendar);

        if (higher == null && lower != null)
            newCalendar = lower;//from  w  w  w  .j a v a 2  s .co  m
        else if (lower == null && higher != null)
            newCalendar = higher;

        if (newCalendar != null || higher == null) {
            newCalendar = newCalendar == null ? calendar : newCalendar;
            newCalendar.setTimeZone(getTimeZone());
            calendar.setTimeInMillis(newCalendar.getTimeInMillis());
            return;
        }

        long highDistance = Math.abs(higher.getTimeInMillis() - calendar.getTimeInMillis());
        long lowDistance = Math.abs(calendar.getTimeInMillis() - lower.getTimeInMillis());

        if (lowDistance < highDistance)
            calendar.setTimeInMillis(lower.getTimeInMillis());
        else
            calendar.setTimeInMillis(higher.getTimeInMillis());

        return;
    }

    if (!disabledDays.isEmpty()) {
        Calendar forwardDate = (Calendar) calendar.clone();
        Calendar backwardDate = (Calendar) calendar.clone();
        while (isDisabled(forwardDate) && isDisabled(backwardDate)) {
            forwardDate.add(Calendar.DAY_OF_MONTH, 1);
            backwardDate.add(Calendar.DAY_OF_MONTH, -1);
        }
        if (!isDisabled(backwardDate)) {
            calendar.setTimeInMillis(backwardDate.getTimeInMillis());
            return;
        }
        if (!isDisabled(forwardDate)) {
            calendar.setTimeInMillis(forwardDate.getTimeInMillis());
            return;
        }
    }

    if (isBeforeMin(calendar)) {
        calendar.setTimeInMillis(mMinDate.getTimeInMillis());
        return;
    }

    if (isAfterMax(calendar)) {
        calendar.setTimeInMillis(mMaxDate.getTimeInMillis());
        return;
    }
}