Example usage for java.util GregorianCalendar setTime

List of usage examples for java.util GregorianCalendar setTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar setTime.

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

From source file:com.opencsv.bean.BeanFieldDate.java

/**
 * Converts the input to/from a calendar object.
 * <p>This method should work for any type that implements
 * {@link java.util.Calendar} or is derived from
 * {@link javax.xml.datatype.XMLGregorianCalendar}. The following types are
 * explicitly supported:/*from  w  w w .  j a  v a  2  s .  co  m*/
 * <ul><li>Calendar (always a GregorianCalendar)</li>
 * <li>GregorianCalendar</li>
 * <li>XMLGregorianCalendar</li></ul>
 * It is also known to work with
 * org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl.</p>
 *
 * @param <U> The type to be converted to
 * @param value The string to be converted into a date/time type or vice
 *   versa
 * @param fieldType The class of the destination field
 * @return The object resulting from the conversion
 * @throws CsvDataTypeMismatchException If the conversion fails
 */
private <U> U convertCalendar(Object value, Class<U> fieldType) throws CsvDataTypeMismatchException {
    U o;

    if (value instanceof String) {
        // Parse input
        Date d;
        try {
            d = getFormat().parse((String) value);
        } catch (ParseException e) {
            CsvDataTypeMismatchException csve = new CsvDataTypeMismatchException(value, fieldType);
            csve.initCause(e);
            throw csve;
        }

        // Make a GregorianCalendar out of it, because this works for all
        // supported types, at least as an intermediate step.
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(d);

        // XMLGregorianCalendar requires special processing.
        if (fieldType == XMLGregorianCalendar.class) {
            try {
                o = fieldType.cast(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
            } catch (DatatypeConfigurationException e) {
                // I've never known how to handle this exception elegantly,
                // especially since I can't conceive of the circumstances
                // under which it is thrown.
                CsvDataTypeMismatchException ex = new CsvDataTypeMismatchException(
                        "It was not possible to initialize an XMLGregorianCalendar.");
                ex.initCause(e);
                throw ex;
            }
        } else {
            o = fieldType.cast(gc);
        }
    } else {
        Calendar c;
        if (value instanceof XMLGregorianCalendar) {
            c = ((XMLGregorianCalendar) value).toGregorianCalendar();
        } else if (value instanceof Calendar) {
            c = (Calendar) value;
        } else {
            throw new CsvDataTypeMismatchException(value, fieldType, NOT_DATE);
        }
        o = fieldType.cast(getFormat().format(c.getTime()));
    }

    return o;
}

From source file:edu.lternet.pasta.portal.statistics.GrowthStats.java

private ArrayList<Integer> buildFrequencies(GregorianCalendar start, GregorianCalendar end, int scale,
        Long[] list) {//from w  w  w .j  a  v a2s  . com

    ArrayList<Integer> freqs = new ArrayList<Integer>();

    GregorianCalendar lower = (GregorianCalendar) start.clone();
    GregorianCalendar upper = new GregorianCalendar();

    while (lower.getTimeInMillis() <= end.getTimeInMillis()) {
        upper.setTime(lower.getTime());
        upper.add(scale, 1);

        int freq = 0;

        for (int i = 0; i < list.length; i++) {
            if (lower.getTimeInMillis() <= list[i] && list[i] < upper.getTimeInMillis()) {
                freq++;
                //System.out.printf("%d - %d - %d - %d%n", lower.getTimeInMillis(), list[i], upper.getTimeInMillis(), freq);
            }
        }
        freqs.add(freq);
        lower.setTime(upper.getTime());

    }

    return freqs;

}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.reservation.ReservationServiceImpl.java

/**
 * {@inheritDoc}//from   www  .j  a  va2s  .c o  m
 */
@Override
@Transactional(readOnly = true)
public ReservationDataList getFromToDate(String fromDate, String toDate) throws RestServiceException {
    GregorianCalendar fromCalendar = new GregorianCalendar();
    GregorianCalendar toCalendar = new GregorianCalendar();
    try {
        fromCalendar.setTime(sf.parse(fromDate));
        toCalendar.setTime(sf.parse(toDate));
        List<Reservation> reservations = reservationDao.getReservationsBetween(fromCalendar, toCalendar);
        List<ReservationData> data = new ArrayList<ReservationData>(reservations.size());

        for (Reservation r : reservations) {
            data.add(new ReservationData(r.getReservationId(), r.getResearchGroup().getTitle(),
                    r.getResearchGroup().getResearchGroupId(), r.getStartTime(), r.getEndTime(),
                    r.getPerson().getGivenname() + " " + r.getPerson().getSurname(), r.getPerson().getEmail(),
                    canRemoveReservation(r)));
        }

        return new ReservationDataList(data);
    } catch (Exception e) {
        log.error(String.format("From date: %s | To date: %s | Error: %s", fromDate, toDate, e.getMessage()),
                e);
        throw new RestServiceException(e);
    }
}

From source file:com.twinflag.coofiletouch.AuthorityUtil.java

public boolean isLaterThanToday(String date) {
    boolean retValue = false;
    if (date != null) {
        int dayDif = 0;
        int year = 0;
        int month = 0;
        int day = 0;
        String monthStr = null;/* ww  w  . j  a  va  2  s  . co m*/
        String dayStr = null;
        Date toCompareDate = null;
        Date currentDate = null;
        Calendar calendar = null;
        String toCompareDateString = null;
        String currentDateString = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        toCompareDateString = "20" + date;
        try {
            toCompareDate = simpleDateFormat.parse(toCompareDateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // ??
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        if (month < 10) {
            monthStr = "0" + month;
        } else {
            monthStr = "" + month;
        }
        day = calendar.get(Calendar.DAY_OF_MONTH);
        if (day < 10) {
            dayStr = "0" + day;
        } else {
            dayStr = "" + day;
        }
        currentDateString = "" + year + monthStr + dayStr;
        try {
            currentDate = simpleDateFormat.parse(currentDateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        GregorianCalendar cal1 = new GregorianCalendar();
        GregorianCalendar cal2 = new GregorianCalendar();
        cal1.setTime(toCompareDate);
        cal2.setTime(currentDate);
        dayDif = (int) ((cal2.getTimeInMillis() - cal1.getTimeInMillis()) / (1000 * 3600 * 24));
        if (dayDif <= 0) {
            retValue = true;
        }
    }
    return retValue;
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.GmdConverter.java

protected void addIdentificationInfo(MetacardImpl metacard, XstreamPathValueTracker pathValueTracker) {

    pathValueTracker.add(new Path(GmdMetacardType.TITLE_PATH), StringUtils.defaultString(metacard.getTitle()));

    GregorianCalendar createdCal = new GregorianCalendar();

    if (metacard.getCreatedDate() != null) {

        createdCal.setTime(metacard.getCreatedDate());
    }/*www .j  a  v  a2 s. c om*/
    createdCal.setTimeZone(UTC_TIME_ZONE);
    pathValueTracker.add(new Path(GmdMetacardType.CREATED_DATE_PATH),
            XSD_FACTORY.newXMLGregorianCalendar(createdCal).toXMLFormat());

    pathValueTracker.add(new Path(GmdMetacardType.CREATED_DATE_TYPE_CODE_PATH), GmdMetacardType.METACARD_URI);
    pathValueTracker.add(new Path(GmdMetacardType.CREATED_DATE_TYPE_CODE_VALUE_PATH), Metacard.CREATED);

    pathValueTracker.add(new Path(GmdMetacardType.ABSTRACT_PATH),
            StringUtils.defaultString(metacard.getDescription()));
    pathValueTracker.add(new Path(GmdMetacardType.POINT_OF_CONTACT_PATH),
            StringUtils.defaultString(metacard.getPointOfContact()));

    pathValueTracker.add(new Path(GmdMetacardType.POINT_OF_CONTACT_ROLE_PATH), (String) null);

    pathValueTracker.add(new Path(GmdMetacardType.LANGUAGE_PATH),
            StringUtils.defaultIfEmpty(Locale.getDefault().getLanguage(), Locale.ENGLISH.getLanguage()));
    addExtent(metacard, pathValueTracker);

}

From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RulesMessageServiceBeanTest.java

@Before
@SneakyThrows//from  w  w  w. j a v  a 2 s .  c  o  m
public void before() {

    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");

    date = sdf.parse("31-08-1982 10:20:56");

    idType = new IDType();
    idType.setValue("value");
    idType.setSchemeID("schemeId");

    codeType = new CodeType();
    codeType.setValue("value");

    delimitedPeriod = new DelimitedPeriod();
    MeasureType durationMeasure = new MeasureType();
    durationMeasure.setUnitCode("unitCode");
    durationMeasure.setValue(new BigDecimal(10));
    delimitedPeriod.setDurationMeasure(durationMeasure);

    GregorianCalendar c = new GregorianCalendar();
    c.setTime(date);

    dateTimeType = new DateTimeType();
    dateTimeType.setDateTime(DatatypeFactory.newInstance().newXMLGregorianCalendar(c));
    delimitedPeriod.setStartDateTime(dateTimeType);
    delimitedPeriod.setEndDateTime(dateTimeType);

    faQueryParameterList = new ArrayList<>();
    FAQueryParameter faQueryParameter = new FAQueryParameter();
    faQueryParameter.setTypeCode(codeType);
    faQueryParameter.setValueCode(codeType);
    faQueryParameter.setValueDateTime(dateTimeType);
    faQueryParameter.setValueID(idType);
    faQueryParameterList.add(faQueryParameter);

    faQuery = new FAQuery();
    faQuery.setID(idType);
    faQuery.setSimpleFAQueryParameters(faQueryParameterList);
    faQuery.setSpecifiedDelimitedPeriod(delimitedPeriod);
    faQuery.setSubmittedDateTime(dateTimeType);
    faQuery.setTypeCode(codeType);

    FLUXFAQueryMessage message = new FLUXFAQueryMessage();
    message.setFAQuery(faQuery);

    fluxfaQueryMessage = new FLUXFAQueryMessage();
    fluxfaQueryMessage.setFAQuery(faQuery);

}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.GmdConverter.java

/**
 * Builds up the xml paths and values to write.
 * Order matters!  Paths should be added in the order they must be written.
 *
 * @param metacard/*www  .  j  a  va  2  s . c o m*/
 * @return XstreamPathValueTracker containing XML paths and values to write
 */
protected XstreamPathValueTracker buildPaths(MetacardImpl metacard) {

    XstreamPathValueTracker pathValueTracker = new XstreamPathValueTracker();

    pathValueTracker.add(new Path("/MD_Metadata/@xmlns"), GmdMetacardType.GMD_NAMESPACE);

    pathValueTracker.add(new Path("/MD_Metadata/@xmlns:" + GmdMetacardType.GCO_PREFIX),
            GmdMetacardType.GCO_NAMESPACE);
    pathValueTracker.add(new Path(GmdMetacardType.FILE_IDENTIFIER_PATH), metacard.getId());

    pathValueTracker.add(new Path(GmdMetacardType.CODE_LIST_VALUE_PATH),
            StringUtils.defaultIfEmpty(metacard.getContentTypeName(), "dataset"));
    pathValueTracker.add(new Path(GmdMetacardType.CODE_LIST_PATH), GmdMetacardType.METACARD_URI);

    pathValueTracker.add(new Path(GmdMetacardType.CONTACT_PATH), (String) null);

    GregorianCalendar modifiedCal = new GregorianCalendar();
    if (metacard.getModifiedDate() != null) {

        modifiedCal.setTime(metacard.getModifiedDate());
    }
    modifiedCal.setTimeZone(UTC_TIME_ZONE);

    pathValueTracker.add(new Path(GmdMetacardType.DATE_TIME_STAMP_PATH),
            XSD_FACTORY.newXMLGregorianCalendar(modifiedCal).toXMLFormat());

    addIdentificationInfo(metacard, pathValueTracker);

    addDistributionInfo(metacard, pathValueTracker);

    return pathValueTracker;

}

From source file:org.opensaml.util.http.HttpResource.java

/** {@inheritDoc} */
public long getLastModifiedTime() throws ResourceException {
    try {/*from   w ww  . j  a  v  a2  s  . co m*/
        final Date lastModDate = DateUtils.parseDate(cachedResourceLastModified);
        final GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(lastModDate);
        return cal.getTimeInMillis();
    } catch (DateParseException e) {
        throw new ResourceException(
                "Unable to parse " + cachedResourceLastModified + " from HTTP last modified header", e);
    }
}

From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java

private Element addTimestamp(Element wsSecurityHeaderElement)
        throws SOAPException, DatatypeConfigurationException {
    if (false == this.addTimestamp) {
        return null;
    }/*from   w  w  w  . j  ava2 s .c o m*/
    Document document = wsSecurityHeaderElement.getOwnerDocument();
    Element timestampElement = document.createElementNS(WSU_NAMESPACE, "wsu:Timestamp");
    timestampElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "TS");
    Attr idAttr = timestampElement.getAttributeNodeNS(WSU_NAMESPACE, "Id");
    timestampElement.setIdAttributeNode(idAttr, true);

    Element createdElement = document.createElementNS(WSU_NAMESPACE, "wsu:Created");
    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    Date now = new Date();
    gregorianCalendar.setTime(now);
    gregorianCalendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
    createdElement.setTextContent(xmlGregorianCalendar.toXMLFormat());
    timestampElement.appendChild(createdElement);

    Element expiresElement = document.createElementNS(WSU_NAMESPACE, "wsu:Expires");
    Date expiresDate = new Date(now.getTime() + 1000 * 60 * 5);
    gregorianCalendar.setTime(expiresDate);
    xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
    expiresElement.setTextContent(xmlGregorianCalendar.toXMLFormat());
    timestampElement.appendChild(expiresElement);
    wsSecurityHeaderElement.appendChild(timestampElement);
    return timestampElement;
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.reservation.ReservationServiceImpl.java

/**
 * {@inheritDoc}/*from  ww  w  .j a va  2 s.  com*/
 */
@Override
@Transactional(readOnly = true)
public ReservationDataList getToDate(String date) throws RestServiceException {
    GregorianCalendar calendarFrom = new GregorianCalendar();
    GregorianCalendar calendarTo = new GregorianCalendar();
    try {
        log.debug(sf.parse(date));
        calendarFrom.setTime(sf.parse(date));
        calendarTo.setTime(sf.parse(date));
        calendarTo.add(Calendar.DAY_OF_MONTH, 1);
        List<Reservation> reservations = reservationDao.getReservationsBetween(calendarFrom, calendarTo);
        List<ReservationData> data = new ArrayList<ReservationData>(reservations.size());

        for (Reservation r : reservations) {
            data.add(new ReservationData(r.getReservationId(), r.getResearchGroup().getTitle(),
                    r.getResearchGroup().getResearchGroupId(), r.getStartTime(), r.getEndTime(),
                    r.getPerson().getGivenname() + " " + r.getPerson().getSurname(), r.getPerson().getEmail(),
                    canRemoveReservation(r)));
        }
        return new ReservationDataList(data);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RestServiceException(e);
    }
}