Example usage for java.util Calendar clear

List of usage examples for java.util Calendar clear

Introduction

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

Prototype

public final void clear() 

Source Link

Document

Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined.

Usage

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractSystemHealthController.java

@RequestMapping(value = ("/show_status_details"), method = RequestMethod.GET)
public String showStatusDetails(@RequestParam(value = "date", required = true) String date,
        @RequestParam(value = "serviceinstanceuuid", required = true) String serviceInstanceUUID,
        @RequestParam(value = "dateformat", required = true) String dateFormat, ModelMap map) {
    logger.debug("### showStatusDetails method starting...(GET)");
    User currentUser = getCurrentUser();
    Calendar zeroHourOfTheTargetDate = Calendar
            .getInstance(TimeZone.getTimeZone(DateTimeUtils.getTimeZone(currentUser)));
    zeroHourOfTheTargetDate.clear();
    // IMPORTANT!!! don't zero out after setting the time zone, won't work.

    SimpleDateFormat sd = new SimpleDateFormat(dateFormat);
    sd.setTimeZone(TimeZone.getTimeZone(DateTimeUtils.getTimeZone(currentUser)));
    try {//w  w w .  ja  v  a2s .c  om
        zeroHourOfTheTargetDate.setTime(sd.parse(date));
    } catch (ParseException e) {
        logger.error("Error found ...", e);
    }
    ServiceInstance serviceInstance = connectorConfigurationManager.getInstanceByUUID(serviceInstanceUUID);
    map.addAttribute("health",
            healthService.getSystemHealth(zeroHourOfTheTargetDate.getTime(), serviceInstance));
    map.addAttribute("notifications", healthService.listNotifications(zeroHourOfTheTargetDate.getTime(),
            DateTimeUtils.getTimeZone(currentUser), 0, 0, serviceInstance));
    map.addAttribute("date", zeroHourOfTheTargetDate.getTime());
    // TODO:FIX this. List service Insatnces if required
    logger.debug("### showStatusDetails method end");
    return "system.health.statusDetails";
}

From source file:org.apache.olingo.client.core.v3.PrimitiveValueTest.java

@Test
public void dateTime() throws EdmPrimitiveTypeException {
    final Calendar expected = Calendar.getInstance();
    expected.clear();
    expected.set(2013, 0, 10, 2, 0, 0);//  w  w w.j  a v  a 2 s  . c o m
    expected.set(Calendar.MILLISECOND, 1667673);

    final ODataValue value = getClient().getObjectFactory().newPrimitiveValueBuilder()
            .setType(EdmPrimitiveTypeKind.DateTime).setValue(expected).build();
    assertEquals(EdmPrimitiveTypeKind.DateTime, value.asPrimitive().getTypeKind());

    final Calendar actual = value.asPrimitive().toCastValue(Calendar.class);
    assertEquals(expected.get(Calendar.YEAR), actual.get(Calendar.YEAR));
    assertEquals(expected.get(Calendar.MONTH), actual.get(Calendar.MONTH));
    assertEquals(expected.get(Calendar.DATE), actual.get(Calendar.DATE));
    assertEquals(expected.get(Calendar.HOUR), actual.get(Calendar.HOUR));
    assertEquals(expected.get(Calendar.MINUTE), actual.get(Calendar.MINUTE));
    assertEquals(expected.get(Calendar.SECOND), actual.get(Calendar.SECOND));
    assertEquals(expected.get(Calendar.MILLISECOND), actual.get(Calendar.MILLISECOND));

    // Timestamp
    final Timestamp timestamp = value.asPrimitive().toCastValue(Timestamp.class);
    assertEquals(expected.get(Calendar.MILLISECOND), timestamp.getNanos() / 1000000);

    assertEquals("2013-01-10T02:27:47.673", value.asPrimitive().toString());
}

From source file:org.apache.olingo.client.core.v3.PrimitiveValueTest.java

@Test
public void dateTimeOffset() throws EdmPrimitiveTypeException {
    final Calendar expected = Calendar.getInstance();
    expected.clear();
    expected.setTimeZone(TimeZone.getTimeZone("GMT"));
    expected.set(2013, 0, 10, 2, 0, 0);//from  w  ww .j  ava 2 s.  co  m
    expected.set(Calendar.MILLISECOND, 22);

    final ODataValue value = getClient().getObjectFactory().newPrimitiveValueBuilder()
            .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(expected).build();
    assertEquals(EdmPrimitiveTypeKind.DateTimeOffset, value.asPrimitive().getTypeKind());

    final Calendar asCalendar = value.asPrimitive().toCastValue(Calendar.class);
    assertEquals(expected.get(Calendar.YEAR), asCalendar.get(Calendar.YEAR));
    assertEquals(expected.get(Calendar.MONTH), asCalendar.get(Calendar.MONTH));
    assertEquals(expected.get(Calendar.DATE), asCalendar.get(Calendar.DATE));
    assertEquals(expected.get(Calendar.HOUR), asCalendar.get(Calendar.HOUR));
    assertEquals(expected.get(Calendar.MINUTE), asCalendar.get(Calendar.MINUTE));
    assertEquals(expected.get(Calendar.SECOND), asCalendar.get(Calendar.SECOND));
    assertEquals(expected.get(Calendar.MILLISECOND), asCalendar.get(Calendar.MILLISECOND));

    final Timestamp asTimestamp = value.asPrimitive().toCastValue(Timestamp.class);
    assertEquals(expected.get(Calendar.MILLISECOND), asTimestamp.getNanos() / 1000000);

    assertEquals("2013-01-10T02:00:00.022Z", value.asPrimitive().toString());

    final ODataValue parsed = getClient().getObjectFactory().newPrimitiveValueBuilder()
            .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(value.asPrimitive().toValue()).build();
    assertEquals(22, parsed.asPrimitive().toCastValue(Calendar.class).get(Calendar.MILLISECOND));
}

From source file:com.microsoft.tfs.util.datetime.LenientDateTimeParser.java

/**
 * Parse a free-form date and time first with the default format for the
 * default locale, then by parsing a list of known formats until one
 * succeeds. If the date cannot be parsed, ParseException is thrown.
 * <p>//from  w  w w  .  j  a v  a2 s.  com
 * WARNING: GMT doesn't parse as a time zone in on my platform (JDK 1.5,
 * Linux). Use UTC in your input instead.
 * <p>
 * This method may be somewhat slow, although it is probably not an area of
 * concern for most programs. Because of the way SimpleDateFormat parses,
 * all of the longer, more precise patterns must be tried first (and these
 * are least likely to be used by the user). This means we must walk an
 * array for each search and common formats are necessarily near the end. In
 * reality, most searches can be done under a few (6) milliseconds on a 3
 * GHz computer.
 * <p>
 * <b>Notes on Default Date and Time</b>
 * <p>
 * The defaultDate and defaultTime parameters control whether the returned
 * Calendar has its date and/or time components set to the current date
 * and/or time (instead of the Date class epoch) when the given date time
 * string matches a pattern that does not specify <b>both</b> date and time
 * components. These parameters do <b>not</b> affect the order in which
 * patterns are tested or the criteria for a pattern match. They simply
 * choose which date or time is returned in the date- or time-only pattern
 * match where one of the components was unspecified. When either
 * defaultDate or defaultTime is false the Date class's epoch (1970/01/01
 * 00:00:00 UTC) is used for the default date or time.
 * <p>
 * Both defaultDate and defaultTime may be set to true, but as these
 * parameters do not affect the matching behavior, a given string missing
 * <b>both</b> date and time components will still match no patterns
 * (causing a ParseException to be thrown).
 *
 * @param dateTimeString
 *        the date string to parse (not null).
 * @param defaultDate
 *        if true and the given date time string matches a time-only
 *        pattern, today's date is used in the returned Calendar. If false
 *        and a time-only pattern is matched, 1970/01/01 is used for the
 *        date. See the method Javadoc for more information.
 * @param defaultTime
 *        if true and the given date time string matches a date-only
 *        pattern, the current time is used in the returned Calendar. If
 *        false and a date-only pattern is matched, 00:00:00 is used for the
 *        date. See the method Javadoc for more information.
 * @return a {@link LenientDateTimeResult} containing the date/time that was
 *         in the given dateTimeString and additional match information.
 * @throws ParseException
 *         if the date time string could not be parsed.
 */
public LenientDateTimeResult parseExtended(String dateTimeString, final boolean defaultDate,
        final boolean defaultTime) throws ParseException {
    Check.notNull(dateTimeString, "dateTimeString"); //$NON-NLS-1$

    final long start = System.currentTimeMillis();
    int i = 0;
    Calendar calendar = Calendar.getInstance(timeZone, locale);
    calendar.clear();

    // Java's SimpleDateFormat.parse() doesn't support some common time
    // zones, so we convert them before parsing.
    dateTimeString = convertUnsupportedTimeZones(dateTimeString);

    for (i = 0; i < expandedFormats.length; i++) {
        final LenientDateTimeFormat format = expandedFormats[i];

        try {
            calendar.setTime(format.getDateFormat().parse(dateTimeString));

            if (defaultDate && format.specifiesDate() == false) {
                /*
                 * We matched a pattern that doesn't specify a date and the
                 * user wants a default of today. Copy now's date info into
                 * ret.
                 */

                final Calendar now = new GregorianCalendar(timeZone, locale);
                calendar.set(Calendar.ERA, now.get(Calendar.ERA));
                calendar.set(Calendar.YEAR, now.get(Calendar.YEAR));
                calendar.set(Calendar.MONTH, now.get(Calendar.MONTH));
                calendar.set(Calendar.DATE, now.get(Calendar.DATE));
            }

            if (defaultTime && format.specifiesTime() == false) {
                /*
                 * We matched a pattern that doesn't specify a time and the
                 * user wants a default of now. Copy the parsed Calendar's
                 * date info into a new time.
                 */

                final Calendar newRet = new GregorianCalendar(timeZone, locale);
                newRet.set(Calendar.ERA, calendar.get(Calendar.ERA));
                newRet.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
                newRet.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
                newRet.set(Calendar.DATE, calendar.get(Calendar.DATE));

                calendar = newRet;
            }

            final String messageFormat = "matched at index {0} in {1} ms: {2}"; //$NON-NLS-1$
            final String message = MessageFormat.format(messageFormat, i, (System.currentTimeMillis() - start),
                    dateTimeString);
            log.trace(message);

            return new LenientDateTimeResult(calendar, format.getDateFormat(), format.specifiesDate(),
                    format.specifiesTime());
        } catch (final ParseException e) {
            // Ignore and keep looping.
        }
    }

    String messageFormat = "no match in {0} ms: {1}"; //$NON-NLS-1$
    String message = MessageFormat.format(messageFormat, (System.currentTimeMillis() - start), dateTimeString);
    log.trace(message);

    messageFormat = Messages.getString("LenientDateTimeParser.UnknownDateFormat"); //$NON-NLS-1$
    message = MessageFormat.format(messageFormat, dateTimeString);
    throw new ParseException(message, 0);
}

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:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java

private LxJsonToken parseTokenResponse(JsonElement response) {
    LxJsonToken tokenResponse;//  ww w . j av a 2 s . co m
    try {
        tokenResponse = socket.getGson().fromJson(response, LxJsonToken.class);
    } catch (JsonParseException e) {
        setError(LxOfflineReason.INTERNAL_ERROR, "Error parsing token response: " + e.getMessage());
        return null;
    }
    Boolean unsecurePass = tokenResponse.unsecurePass;
    if (unsecurePass != null && unsecurePass) {
        logger.warn("[{}] Unsecure user password on Miniserver.", debugId);
    }
    long secondsToExpiry;
    Integer validUntil = tokenResponse.validUntil;
    if (validUntil == null) {
        secondsToExpiry = TOKEN_REFRESH_DEFAULT_SECONDS;
    } else {
        // validUntil is the end of token life-span in seconds from 2009/01/01
        Calendar loxoneCalendar = Calendar.getInstance();
        loxoneCalendar.clear();
        loxoneCalendar.set(2009, Calendar.JANUARY, 1);
        loxoneCalendar.add(Calendar.SECOND, validUntil);
        Calendar ohCalendar = Calendar.getInstance();
        secondsToExpiry = (loxoneCalendar.getTimeInMillis() - ohCalendar.getTimeInMillis()) / 1000;
        if (logger.isDebugEnabled()) {
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                logger.debug("[{}] Token will expire on: {}.", debugId,
                        format.format(loxoneCalendar.getTime()));
            } catch (IllegalArgumentException e) {
                logger.debug("[{}] Token will expire in {} days.", debugId,
                        TimeUnit.SECONDS.toDays(secondsToExpiry));
            }
        }
        if (secondsToExpiry <= 0) {
            logger.warn("[{}] Time to token expiry is negative or zero: {}", debugId, secondsToExpiry);
            secondsToExpiry = TOKEN_REFRESH_DEFAULT_SECONDS;
        } else {
            int correction = TOKEN_REFRESH_SECONDS_BEFORE_EXPIRY;
            while (secondsToExpiry - correction < 0) {
                correction /= 2;
            }
            secondsToExpiry -= correction;
        }
    }
    scheduleTokenRefresh(secondsToExpiry);
    return tokenResponse;
}

From source file:org.jfree.data.time.Day.java

/**
 * Returns the first millisecond of the day, evaluated using the supplied
 * calendar (which determines the time zone).
 *
 * @param calendar  calendar to use (<code>null</code> not permitted).
 *
 * @return The start of the day as milliseconds since 01-01-1970.
 *
 * @throws NullPointerException if <code>calendar</code> is
 *     <code>null</code>./*from  w  w  w .  j a v  a  2s  . c om*/
 */
@Override
public long getFirstMillisecond(Calendar calendar) {
    int year = this.serialDate.getYYYY();
    int month = this.serialDate.getMonth();
    int day = this.serialDate.getDayOfMonth();
    calendar.clear();
    calendar.set(year, month - 1, day, 0, 0, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTimeInMillis();
}

From source file:org.jfree.data.time.Day.java

/**
 * Returns the last millisecond of the day, evaluated using the supplied
 * calendar (which determines the time zone).
 *
 * @param calendar  calendar to use (<code>null</code> not permitted).
 *
 * @return The end of the day as milliseconds since 01-01-1970.
 *
 * @throws NullPointerException if <code>calendar</code> is
 *     <code>null</code>./* w  ww .ja  v a  2s . c  o m*/
 */
@Override
public long getLastMillisecond(Calendar calendar) {
    int year = this.serialDate.getYYYY();
    int month = this.serialDate.getMonth();
    int day = this.serialDate.getDayOfMonth();
    calendar.clear();
    calendar.set(year, month - 1, day, 23, 59, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTimeInMillis();
}

From source file:org.jfree.data.time.Minute.java

/**
 * Returns the first millisecond of the minute.
 *
 * @param calendar  the calendar which defines the timezone
 *     (<code>null</code> not permitted).
 *
 * @return The first millisecond./*from  w  ww  .j av  a2  s. com*/
 *
 * @throws NullPointerException if <code>calendar</code> is
 *     <code>null</code>.
 */
@Override
public long getFirstMillisecond(Calendar calendar) {
    int year = this.day.getYear();
    int month = this.day.getMonth() - 1;
    int d = this.day.getDayOfMonth();

    calendar.clear();
    calendar.set(year, month, d, this.hour, this.minute, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTimeInMillis();
}

From source file:org.jfree.data.time.Minute.java

/**
 * Returns the last millisecond of the minute.
 *
 * @param calendar  the calendar / timezone (<code>null</code> not
 *     permitted)./*from  w  w w. j  av a2 s  .com*/
 *
 * @return The last millisecond.
 *
 * @throws NullPointerException if <code>calendar</code> is
 *     <code>null</code>.
 */
@Override
public long getLastMillisecond(Calendar calendar) {
    int year = this.day.getYear();
    int month = this.day.getMonth() - 1;
    int d = this.day.getDayOfMonth();

    calendar.clear();
    calendar.set(year, month, d, this.hour, this.minute, 59);
    calendar.set(Calendar.MILLISECOND, 999);

    return calendar.getTimeInMillis();
}