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.betaconceptframework.astroboa.model.jaxb.visitor.ContentObjectMarshalVisitor.java

protected <T> void marshallValueForSimpleProperty(SimpleCmsPropertyDefinition<T> simplePropertyDefinition,
        CmsPropertyInfo simpleCmsProperty, Object value) {

    if (value != null) {

        switch (simplePropertyDefinition.getValueType()) {
        case String:
        case Boolean:
        case Double:
        case Long:
        case Date:

            final SimpleCmsPropertyType simpleCmsPropertyType = new SimpleCmsPropertyType();

            simpleCmsPropertyType.setExportAsAnAttribute(
                    ((SimpleCmsPropertyDefinitionImpl) simplePropertyDefinition).isRepresentsAnXmlAttribute());

            if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                simpleCmsPropertyType.setExportAsAnArray(true);
            }//w w w. j a v  a2 s . c o  m

            CmsPropertyTypeJAXBElement<SimpleCmsPropertyType> simpleCmsPropertyTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                    new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()),
                    SimpleCmsPropertyType.class, null, simpleCmsPropertyType);

            if (value instanceof String) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent((String) value);
            } else if (value instanceof Boolean) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent(((Boolean) value).toString());
            } else if (value instanceof Double) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent(((Double) value).toString());
            } else if (value instanceof Long) {
                simpleCmsPropertyTypeJaxbElement.getValue().setContent(((Long) value).toString());
            } else if (value instanceof Calendar) {
                Calendar calendar = (Calendar) value;

                try {
                    if (((CalendarPropertyDefinition) simplePropertyDefinition).isDateTime()) {
                        GregorianCalendar gregCalendar = new GregorianCalendar(calendar.getTimeZone());
                        gregCalendar.setTimeInMillis(calendar.getTimeInMillis());

                        simpleCmsPropertyTypeJaxbElement.getValue()
                                .setContent(df.newXMLGregorianCalendar(gregCalendar).toXMLFormat());
                    } else {
                        simpleCmsPropertyTypeJaxbElement.getValue()
                                .setContent(df.newXMLGregorianCalendarDate(calendar.get(Calendar.YEAR),
                                        calendar.get(Calendar.MONTH) + 1, // Calendar.MONTH is zero based, XSD Date datatype's month field starts
                                        //   with JANUARY as 1.
                                        calendar.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED)
                                        .toXMLFormat());
                    }
                } catch (Exception e) {
                    throw new CmsException("Property " + simpleCmsProperty.getFullPath() + " Calendar value "
                            + DateUtils.format(calendar), e);
                }
            } else {
                throw new CmsException("Property " + simpleCmsProperty.getFullPath() + " has value type "
                        + simplePropertyDefinition.getValueType() + " but contains value of type "
                        + value.getClass().getName());
            }

            addJaxbElementToCurrentParentComplexCmsPropertyType(simpleCmsPropertyTypeJaxbElement);

            break;
        case TopicReference:

            try {
                TopicType topicType = marshalTopicReference(value);

                if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                    topicType.setExportAsAnArray(true);
                }

                CmsPropertyTypeJAXBElement<TopicType> topicTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                        new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()), TopicType.class,
                        null, topicType);

                addJaxbElementToCurrentParentComplexCmsPropertyType(topicTypeJaxbElement);

            } catch (Exception e) {
                throw new CmsException("Unable to marshal topic " + ((Topic) value).getName(), e);
            }

            break;
        case Binary:
            try {
                BinaryChannelType binaryChannelType = getBinaryChannelAdapter().marshal((BinaryChannel) value);

                if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                    binaryChannelType.setExportAsAnArray(true);
                }

                CmsPropertyTypeJAXBElement<BinaryChannelType> binaryChannelTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                        new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()),
                        BinaryChannelType.class, null, binaryChannelType);

                addJaxbElementToCurrentParentComplexCmsPropertyType(binaryChannelTypeJaxbElement);

            } catch (Exception e) {
                throw new CmsException("Unable to marshal binary channel " + ((BinaryChannel) value).getName(),
                        e);
            }

            break;
        case ObjectReference:
            try {

                logger.debug("\t Property is a reference to another object");

                Marshaller objectReferenceMarshaller = CmsEntitySerialization.Context
                        .createMarshaller(marshalOutputTypeIsJSON() ? ResourceRepresentationType.JSON
                                : ResourceRepresentationType.XML, prettyPrintIsEnabled());

                //For now only porifle.title is provided. 
                objectReferenceMarshaller.setProperty(AstroboaMarshaller.CMS_PROPERTIES_TO_BE_MARSHALLED,
                        Arrays.asList("profile.title"));

                ContentObjectAdapter adapter = new ContentObjectAdapter();
                adapter.setMarshaller(objectReferenceMarshaller, marshallBinaryContent, false);
                objectReferenceMarshaller.setAdapter(adapter);

                ContentObjectType contentObjectType = objectReferenceMarshaller
                        .getAdapter(ContentObjectAdapter.class).marshal((ContentObject) value);

                if (marshalOutputTypeIsJSON() && simplePropertyDefinition.isMultiple()) {
                    contentObjectType.setExportAsAnArray(true);
                }

                CmsPropertyTypeJAXBElement<ContentObjectType> contentObjectReferenceTypeJaxbElement = new CmsPropertyTypeJAXBElement(
                        new QName(simplePropertyDefinition.getQualifiedName().getLocalPart()),
                        ContentObjectType.class, null, contentObjectType);

                addJaxbElementToCurrentParentComplexCmsPropertyType(contentObjectReferenceTypeJaxbElement);

            } catch (Exception e) {
                throw new CmsException("Unable to marshal contentObject " + ((ContentObject) value).getId(), e);
            }

            break;
        default:
            break;
        }

    }
}

From source file:org.shampoo.goldenembed.parser.GoldenEmbedParserMain.java

private String createRideDate(GPS gps, byte[] timeStamp) {

    String strYear = "20" + timeStamp[0];
    int year = Integer.valueOf(strYear);
    int month = timeStamp[1];
    month--; // Zero based
    int day = timeStamp[2];

    int hr = timeStamp[3];
    int min = timeStamp[4];
    int sec = timeStamp[5];

    Calendar rideCal = new GregorianCalendar();
    rideCal.set(year, month, day, hr, min, sec);

    SimpleDateFormat rideFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    rideFormat.setTimeZone(rideCal.getTimeZone());
    rideDate = rideFormat.format(rideCal.getTime());

    return rideDate;

}

From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java

public String calendarTime24HrString(Context context, @NonNull Calendar cal, boolean showSeconds) {
    Locale locale = getLocale();/*from  ww w .jav a2s .  co  m*/
    String format = (showSeconds ? strTimeVeryShortFormat24s : strTimeVeryShortFormat24); // HH:mm or HH:mm:ss
    SimpleDateFormat timeFormat = new SimpleDateFormat(format, locale);
    timeFormat.setTimeZone(cal.getTimeZone());
    return timeFormat.format(cal.getTime());
}

From source file:org.apache.jackrabbit.core.persistence.util.BundleWriter.java

/**
 * Serializes a JCR date value using the {@link #writeVarLong(long)}
 * serialization on a special 64-bit date encoding. This encoding maps
 * the <code>sYYYY-MM-DDThh:mm:ss.sssTZD</code> date format used by
 * JCR to an as small 64 bit integer (positive or negative) as possible,
 * while preserving full accuracy (including time zone offsets) and
 * favouring common levels of accuracy (per minute, hour and day) over
 * full millisecond level detail.//from w w  w .  j a v a  2 s .  c  om
 * <p>
 * Each date value is mapped to separate timestamp and timezone fields,
 * both of whose lenghts are variable: 
 * <pre>
 * +----- ... ------- ... --+
 * |  timestamp  | timezone |
 * +----- ... ------- ... --+
 * </pre>
 * <p>
 * The type and length of the timezone field can be determined by looking
 * at the two least significant bits of the value:
 * <dl>
 *   <dt><code>?0</code></dt>
 *   <dd>
 *     UTC time. The length of the timezone field is just one bit,
 *     i.e. the second bit is already a part of the timestamp field.
 *   </dd>
 *   <dt><code>01</code></dt>
 *   <dd>
 *     The offset is counted as hours from UTC, and stored as the number
 *     of hours (positive or negative) in the next 5 bits (range from
 *     -16 to +15 hours), making the timezone field 7 bits long in total.
 *   </dd>
 *   <dt><code>11</code></dt>
 *   <dd>
 *     The offset is counted as hours and minutes from UTC, and stored
 *     as the total minute offset (positive or negative) in the next
 *     11 bits (range from -17 to +17 hours), making the timezone field
 *     13 bits long in total.
 *   </dd>
 * </dl>
 * <p>
 * The remaining 51-63 bits of the encoded value make up the timestamp
 * field that also uses the two least significant bits to indicate the
 * type and length of the field:
 * <dl>
 *   <dt><code>00</code></dt>
 *   <dd>
 *     <code>sYYYY-MM-DDT00:00:00.000</code>, i.e. midnight of the
 *     specified date. The next 9 bits encode the day within the year
 *     (starting from 1, maximum value 366) and the remaining bits are
 *     used for the year, stored as an offset from year 2010.
 *   </dd>
 *   <dt><code>01</code></dt>
 *   <dd>
 *     <code>sYYYY-MM-DDThh:00:00.000</code>, i.e. at the hour. The
 *     next 5 bits encode the hour within the day (starting from 0,
 *     maximum value 23) and the remaining bits are used as described
 *     above for the date.
 *   </dd>
 *   <dt><code>10</code></dt>
 *   <dd>
 *     <code>sYYYY-MM-DDThh:mm:00.000</code>, i.e. at the minute. The
 *     next 11 bits encode the minute within the day (starting from 0,
 *     maximum value 1439) and the remaining bits are used as described
 *     above for the date.
 *   </dd>
 *   <dt><code>11</code></dt>
 *   <dd>
 *     <code>sYYYY-MM-DDThh:mm:ss.sss</code>, i.e. full millisecond
 *     accuracy. The next 30 bits encode the millisecond within the
 *     day (starting from 0, maximum value 87839999) and the remaining
 *     bits are used as described above for the date.
 *   </dd>
 * </dl>
 * <p>
 * With full timezone and millisecond accuracies, this encoding leaves
 * 10 bits (64 - 9 - 30 - 2 - 11 - 2) for the date offset, which allows
 * for representation of all timestamps between years 1498 and 2521.
 * Timestamps outside this range and with a minute-level timezone offset
 * are automatically truncated to minute-level accuracy to support the
 * full range of years -9999 to 9999 specified in JCR.
 * <p>
 * Note that the year, day of year, and time of day values are stored
 * as separate bit sequences to avoid problems with changing leap second
 * or leap year definitions. Bit fields are used for better encoding and
 * decoding performance than what would be possible with the slightly more
 * space efficient mechanism of using multiplication and modulo divisions
 * to separate the different timestamp fields.
 *
 * @param value date value
 * @throws IOException if an I/O error occurs
 */
private void writeDate(Calendar value) throws IOException {
    int y = value.get(Calendar.YEAR);
    if (value.isSet(Calendar.ERA) && value.get(Calendar.ERA) == GregorianCalendar.BC) {
        y = 1 - y; // convert to an astronomical year
    }
    y -= 2010; // use a recent offset NOTE: do not change this!

    int d = value.get(Calendar.DAY_OF_YEAR);
    int h = value.get(Calendar.HOUR_OF_DAY);
    int m = value.get(Calendar.MINUTE);
    int s = value.get(Calendar.SECOND);
    int u = value.get(Calendar.MILLISECOND);
    int z = value.getTimeZone().getOffset(value.getTimeInMillis()) / (60 * 1000);
    int zh = z / 60;
    int zm = z - zh * 60;

    long ts = y << 9 | d & 0x01ff;

    if ((u != 0 || s != 0) && ((-512 <= y && y < 512) || zm == 0)) {
        ts <<= 30;
        ts |= (((h * 60 + m) * 60 + s) * 1000 + u) & 0x3fffffff; // 30 bits
        ts <<= 2;
        ts |= 3;
    } else if (m != 0) {
        ts <<= 11;
        ts |= (h * 60 + m) & 0x07ff; // 11 bits
        ts <<= 2;
        ts |= 2;
    } else if (h != 0) {
        ts <<= 5;
        ts |= h & 0x1f; // 5 bits
        ts <<= 2;
        ts |= 1;
    } else {
        ts <<= 2;
    }

    if (zm != 0) {
        ts <<= 11;
        ts |= z & 0x07ff; // 11 bits
        writeVarLong(ts << 2 | 3);
    } else if (zh != 0) {
        ts <<= 5;
        ts |= zh & 0x1f; // 5 bits
        writeVarLong(ts << 2 | 1);
    } else {
        writeVarLong(ts << 1);
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.Mapper.java

/**
 * Returns a loggable value using pseudo-SQL syntax.
 *//* w  w  w  .  jav  a2  s.  c o  m*/
@SuppressWarnings("boxing")
private static String loggedValue(Serializable value) {
    if (value == null) {
        return "NULL";
    }
    if (value instanceof String) {
        String v = (String) value;
        if (v.length() > DEBUG_MAX_STRING) {
            v = v.substring(0, DEBUG_MAX_STRING) + "...(" + v.length() + " chars)...";
        }
        return "'" + v.replace("'", "''") + "'";
    }
    if (value instanceof Calendar) {
        Calendar cal = (Calendar) value;
        char sign;
        int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis()) / 60000;
        if (offset < 0) {
            offset = -offset;
            sign = '-';
        } else {
            sign = '+';
        }
        return String.format("TIMESTAMP '%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d'",
                cal.get(Calendar.YEAR), //
                cal.get(Calendar.MONTH) + 1, //
                cal.get(Calendar.DAY_OF_MONTH), //
                cal.get(Calendar.HOUR_OF_DAY), //
                cal.get(Calendar.MINUTE), //
                cal.get(Calendar.SECOND), //
                cal.get(Calendar.MILLISECOND), //
                sign, offset / 60, offset % 60);
    }
    if (value instanceof Binary) {
        return "'" + ((Binary) value).getDigest() + "'";
    }
    if (value.getClass().isArray()) {
        Serializable[] v = (Serializable[]) value;
        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; i < v.length; i++) {
            if (i > 0) {
                b.append(',');
                if (i > DEBUG_MAX_ARRAY) {
                    b.append("...(" + v.length + " items)...");
                    break;
                }
            }
            b.append(loggedValue(v[i]));
        }
        b.append(']');
        return b.toString();
    }
    return value.toString();
}

From source file:org.verdictdb.jdbc41.VerdictResultSet.java

@Override
public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException {
    try {/* w  w w .  j ava2 s  . c  om*/
        FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS", cal.getTimeZone());
        return new Timestamp(dateFormat.parse(queryResult.getTimestamp(columnIndex - 1).toString()).getTime());
    } catch (Exception e) {
        SQLException error = new SQLException("Error parsing time stamp");
        throw error;
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean.java

private String generateXMLRepresentationOfCalendar(Calendar calendar) {

    if (calendar == null) {
        calendar = Calendar.getInstance();
    }//from w  ww  .  j a v a  2  s.  co m

    try {
        DatatypeFactory df = DatatypeFactory.newInstance();
        GregorianCalendar gregCalendar = new GregorianCalendar(calendar.getTimeZone());
        gregCalendar.setTimeInMillis(calendar.getTimeInMillis());

        return df.newXMLGregorianCalendar(gregCalendar).toXMLFormat();

    } catch (DatatypeConfigurationException e) {
        return null;
    }

}

From source file:com.sunrun.crportal.util.CRPortalUtil.java

public static Calendar setNewCalendar(Calendar oldCalendar, TimeZone tz) {

    LOG.debug("* ---------------------------------------------------------- *");
    LOG.debug("* setNewCalendar - Entering                                  *");
    LOG.debug("* ---------------------------------------------------------- *");

    SimpleDateFormat sdf = new SimpleDateFormat(df);
    //sdf.setTimeZone(tz);
    LOG.debug("   setNewCalendar - oldCalendar = " + sdf.format(oldCalendar.getTimeInMillis()));
    LOG.debug("   setNewCalendar - TimeZone    = " + tz.getID());

    Calendar newCalendar = null;

    DateFormat dfm;//from w w  w  . j  a  v  a 2 s  .  c o  m
    int intDay;
    int intMonth;
    int intYear;
    Date dtRightNow = null;
    String strRightNow;

    intDay = oldCalendar.get(Calendar.DAY_OF_MONTH);
    intMonth = oldCalendar.get(Calendar.MONTH);
    intYear = oldCalendar.get(Calendar.YEAR);

    strRightNow = "";
    strRightNow += intYear;
    strRightNow += "-";
    strRightNow += intMonth + 1;
    strRightNow += "-";
    strRightNow += intDay;
    LOG.debug("   setCalendar - strRightNow = " + strRightNow);
    try {
        dfm = new SimpleDateFormat("yyyy-MM-dd");
        //dfm.setTimeZone(tz);
        dtRightNow = dfm.parse(strRightNow);
        newCalendar = Calendar.getInstance(tz);
        newCalendar.setTime(dtRightNow);
        LOG.debug("   setNewCalendar - newCalendar    = " + sdf.format(newCalendar.getTimeInMillis()));
        LOG.debug("   setNewCalendar - newCalendar TZ = " + newCalendar.getTimeZone().getID());
    } catch (java.text.ParseException e) {
        LOG.warn(e.getMessage());
        LOG.debug("   setNewCalendar - defaultFromDate = null");
    }

    LOG.debug("* ---------------------------------------------------------- *");
    LOG.debug("* setNewCalendar - Exiting                                   *");
    LOG.debug("* ---------------------------------------------------------- *");
    return newCalendar;
}

From source file:org.opencms.search.CmsSearchIndex.java

/**
 * Generates a list of date terms for the optimized date range search with "daily" granularity level.<p> 
 * /*from  ww  w . j a  v a2 s  . c o m*/
 * How this works:<ul>
 * <li>For each document, terms are added for the year, the month and the day the document
 * was modified or created) in. So for example if a document is modified at February 02, 2009, 
 * then the following terms are stored for this document:
 * "20090202", "200902" and "2009".</li>
 * <li>In case a date range search is done, then all possible matches for the
 * provided rage are created as search terms and matched with the document terms.</li>
 * <li>Consider the following use case: You want to find out if a resource has been changed
 * in the time between November 29, 2007 and March 01, 2009.
 * One term to match is simply "2008" because if a document 
 * was modified in 2008, then it is clearly in the date range.
 * Other terms are "200712", "200901" and "200902", because all documents 
 * modified in these months are also a certain matches.
 * Finally we need to add terms for "20071129", "20071130" and "20090301" to match the days in the 
 * starting and final month.</li>
 * </ul>
 * 
 * @param startDate start date of the range to search in
 * @param endDate end date of the range to search in
 * 
 * @return a list of date terms for the optimized date range search
 */
public static List<String> getDateRangeSpan(long startDate, long endDate) {

    if (startDate > endDate) {
        // switch so that the end is always before the start
        long temp = endDate;
        endDate = startDate;
        startDate = temp;
    }

    List<String> result = new ArrayList<String>(100);

    // initialize calendars from the time value
    Calendar calStart = Calendar.getInstance(OpenCms.getLocaleManager().getTimeZone());
    Calendar calEnd = Calendar.getInstance(calStart.getTimeZone());
    calStart.setTimeInMillis(startDate);
    calEnd.setTimeInMillis(endDate);

    // get the required info to build the date range from the calendars
    int startDay = calStart.get(Calendar.DAY_OF_MONTH);
    int endDay = calEnd.get(Calendar.DAY_OF_MONTH);
    int maxDayInStartMonth = calStart.getActualMaximum(Calendar.DAY_OF_MONTH);
    int startMonth = calStart.get(Calendar.MONTH) + 1;
    int endMonth = calEnd.get(Calendar.MONTH) + 1;
    int startYear = calStart.get(Calendar.YEAR);
    int endYear = calEnd.get(Calendar.YEAR);

    // first add all full years in the date range
    result.addAll(getYearSpan(startYear + 1, endYear - 1));

    if (startYear != endYear) {
        // different year, different month
        result.addAll(getMonthSpan(startMonth + 1, 12, startYear));
        result.addAll(getMonthSpan(1, endMonth - 1, endYear));
        result.addAll(getDaySpan(startDay, maxDayInStartMonth, startMonth, startYear));
        result.addAll(getDaySpan(1, endDay, endMonth, endYear));
    } else {
        if (startMonth != endMonth) {
            // same year, different month
            result.addAll(getMonthSpan(startMonth + 1, endMonth - 1, startYear));
            result.addAll(getDaySpan(startDay, maxDayInStartMonth, startMonth, startYear));
            result.addAll(getDaySpan(1, endDay, endMonth, endYear));
        } else {
            // same year, same month
            result.addAll(getDaySpan(startDay, endDay, endMonth, endYear));
        }
    }

    // sort the result, makes the range better readable in the debugger
    Collections.sort(result);
    return result;
}