Example usage for java.util Calendar setLenient

List of usage examples for java.util Calendar setLenient

Introduction

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

Prototype

public void setLenient(boolean lenient) 

Source Link

Document

Specifies whether or not date/time interpretation is to be lenient.

Usage

From source file:Main.java

/**
 * Parse a date from ISO-8601 formatted string. It expects a format yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
 *
 * @param date ISO string to parse in the appropriate format.
 * @return the parsed date/*www.  jav  a 2s.  c  om*/
 * @throws IllegalArgumentException if the date is not in the appropriate format
 */
public static Date parse(String date) {
    try {
        int offset = 0;

        // extract year
        int year = parseInt(date, offset, offset += 4);
        checkOffset(date, offset, '-');

        // extract month
        int month = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, '-');

        // extract day
        int day = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, 'T');

        // extract hours, minutes, seconds and milliseconds
        int hour = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, ':');

        int minutes = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, ':');

        int seconds = parseInt(date, offset += 1, offset += 2);
        // milliseconds can be optional in the format
        int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time
        if (date.charAt(offset) == '.') {
            checkOffset(date, offset, '.');
            milliseconds = parseInt(date, offset += 1, offset += 3);
        }

        // extract timezone
        String timezoneId;
        char timezoneIndicator = date.charAt(offset);
        if (timezoneIndicator == '+' || timezoneIndicator == '-') {
            timezoneId = GMT_ID + date.substring(offset);
        } else if (timezoneIndicator == 'Z') {
            timezoneId = GMT_ID;
        } else {
            throw new IndexOutOfBoundsException("Invalid time zone indicator " + timezoneIndicator);
        }
        TimeZone timezone = TimeZone.getTimeZone(timezoneId);
        if (!timezone.getID().equals(timezoneId)) {
            throw new IndexOutOfBoundsException();
        }

        Calendar calendar = new GregorianCalendar(timezone);
        calendar.setLenient(false);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, milliseconds);

        return calendar.getTime();
    } catch (IndexOutOfBoundsException e) {
        throw new IllegalArgumentException("Failed to parse date " + date, e);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("Failed to parse date " + date, e);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Failed to parse date " + date, e);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.util.DateUtils.java

/**
 * Checks if the date represented by the passed parameters is valid.
 * All parameters are 1-based meaning 1 for Jan, 2 for Feb etc unlike Java Calendar API
 *
 * @param day date value for the date (1-based)
 * @param month month value for the date (1-based)
 * @param year year value for the date (1-based)
 * @return  the <code>Date</code> if valid, <code>null</code> otherwise
 * @throws DateUtilsException if the date does not have the expected format
 *//*  w  ww.  j  a  v  a 2  s.  co  m*/
public static Date validate(final String day, final String month, final String year) throws DateUtilsException {

    Date result = null;

    if (validateDateFormat(day, month, year)) {

        final Calendar cal = Calendar.getInstance();
        cal.setLenient(false);
        cal.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day), 0, 0, 0);
        cal.set(Calendar.MILLISECOND, 0);

        try {
            //Important : getTime has to be called to find out that the date is correct.
            result = cal.getTime();

        } catch (IllegalArgumentException e) {
            // this exception is thrown by the Java Calender getTime Method, if the date is not valid
        }
    }

    return result;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.util.DateUtils.java

/**
 * Return <code>true</code> if the date represented by the passed parameters is strictly before the given upper limit,
 * <code>false</code> otherwise.
 *
 * Note: All parameters are 1-based meaning 1 for Jan, 2 for Feb etc unlike Java Calendar API.
 *
 * @param day date value for the date/*from  w ww .ja v a 2 s .c o  m*/
 * @param month month value for the date
 * @param year year value for the date
 * @param strictUpperLimit the strict upper limit for the given date
 * @return <code>true</code> if the date represented by the passed parameters is strictly before the given upper limit,
 * <code>false</code> otherwise
 */
public static boolean isDateStrictlyBeforeGivenTime(final String day, final String month, final String year,
        final Calendar strictUpperLimit) {

    boolean result = true;

    final Calendar calendarFromDate = Calendar.getInstance();
    calendarFromDate.setLenient(false);
    calendarFromDate.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day), 0, 0, 0);
    calendarFromDate.set(Calendar.MILLISECOND, 0);

    if (!calendarFromDate.before(strictUpperLimit)) {
        result = false;
    }

    return result;
}

From source file:Main.java

/**
 * Parse a date from ISO-8601 formatted string. It expects a format
 * yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
 *
 * @param date ISO string to parse in the appropriate format.
 * @return the parsed date/*from   w  w w  . j  a v  a2  s.  c o m*/
 * @throws IllegalArgumentException if the date is not in the appropriate format
 */
public static Date parse(String date) {
    try {
        int offset = 0;

        // extract year
        int year = parseInt(date, offset, offset += 4);
        checkOffset(date, offset, '-');

        // extract month
        int month = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, '-');

        // extract day
        int day = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, 'T');

        // extract hours, minutes, seconds and milliseconds
        int hour = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, ':');

        int minutes = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, ':');

        int seconds = parseInt(date, offset += 1, offset += 2);
        // milliseconds can be optional in the format
        // always use 0 otherwise returned date will include millis of current time
        int milliseconds = 0;

        if (date.charAt(offset) == '.') {
            checkOffset(date, offset, '.');
            int digitCount = 1;
            while (offset + digitCount < date.length() && digitCount < 3
                    && date.charAt(offset + 1 + digitCount) != 'Z'
                    && date.charAt(offset + 1 + digitCount) != '+'
                    && date.charAt(offset + 1 + digitCount) != '-') {
                digitCount++;
            }
            String msString = date.substring(offset += 1, offset += digitCount);
            while (msString.length() < 3) {
                msString += '0';
            }
            milliseconds = parseInt(msString, 0, 3);
        }

        // extract timezone
        String timezoneId = null;
        while (offset < date.length()) {
            char timezoneIndicator = date.charAt(offset);
            if (timezoneIndicator == '+' || timezoneIndicator == '-') {
                timezoneId = GMT_ID + date.substring(offset);
                break;
            } else if (timezoneIndicator == 'Z') {
                timezoneId = GMT_ID;
                break;
            }
            offset++;
        }
        if (timezoneId == null) {
            throw new IndexOutOfBoundsException("Invalid time zone indicator ");
        }
        TimeZone timezone = TimeZone.getTimeZone(timezoneId);
        if (!timezone.getID().equals(timezoneId)) {
            throw new IndexOutOfBoundsException();
        }

        Calendar calendar = new GregorianCalendar(timezone);
        calendar.setLenient(false);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, milliseconds);

        return calendar.getTime();
    } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
        throw new IllegalArgumentException("Failed to parse date " + date, e);
    }
}

From source file:com.sirma.itt.seip.time.ISO8601DateFormat.java

/**
 * Parse date from ISO formatted string.
 *
 * @param isoDate//  ww w. j  ava2s.  c  o m
 *            ISO string to parse
 * @return the date
 */
public static Date parse(String isoDate) {
    if (StringUtils.isBlank(isoDate)) {
        return null;
    }
    Date parsed = null;

    try {
        int offset = 0;

        // extract year
        int year = Integer.parseInt(isoDate.substring(offset, offset += 4));
        if (isoDate.charAt(offset) != '-') {
            throw new IndexOutOfBoundsException(EXPECTED_CHARACTER_BUT_FOUND + isoDate.charAt(offset));
        }

        // extract month
        int month = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != '-') {
            throw new IndexOutOfBoundsException(EXPECTED_CHARACTER_BUT_FOUND + isoDate.charAt(offset));
        }

        // extract day
        int day = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != 'T') {
            throw new IndexOutOfBoundsException("Expected T character but found " + isoDate.charAt(offset));
        }

        // extract hours, minutes, seconds and milliseconds
        int hour = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != ':') {
            throw new IndexOutOfBoundsException(EXPECTED_CHARACTER_BUT_FOUND2 + isoDate.charAt(offset));
        }
        int minutes = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != ':') {
            throw new IndexOutOfBoundsException(EXPECTED_CHARACTER_BUT_FOUND2 + isoDate.charAt(offset));
        }
        int seconds = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        int milliseconds = 0;
        if (isoDate.charAt(offset) == '.') {
            // ALF-3803 bug fix, milliseconds are optional
            milliseconds = Integer.parseInt(isoDate.substring(offset += 1, offset += 3));
        }

        // extract timezone
        String timezoneId;
        char timezoneIndicator = isoDate.charAt(offset);
        if (timezoneIndicator == '+' || timezoneIndicator == '-') {
            timezoneId = "GMT" + isoDate.substring(offset);
        } else if (timezoneIndicator == 'Z') {
            timezoneId = "GMT";
        } else {
            throw new IndexOutOfBoundsException("Invalid time zone indicator " + timezoneIndicator);
        }

        // Get the timezone
        Map<String, TimeZone> timezoneMap = TIMEZONES.get();
        if (timezoneMap == null) {
            timezoneMap = new HashMap<>(3);
            TIMEZONES.set(timezoneMap);
        }
        TimeZone timezone = timezoneMap.get(timezoneId);
        if (timezone == null) {
            timezone = TimeZone.getTimeZone(timezoneId);
            timezoneMap.put(timezoneId, timezone);
        }
        if (!timezone.getID().equals(timezoneId)) {
            throw new IndexOutOfBoundsException();
        }

        // initialize Calendar object#
        // Note: always de-serialise from Gregorian Calendar
        Calendar calendar = new GregorianCalendar(timezone);
        calendar.setLenient(false);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, milliseconds);

        // extract the date
        parsed = calendar.getTime();
    } catch (IndexOutOfBoundsException e) {
        throw new EmfRuntimeException(FAILED_TO_PARSE_DATE + isoDate, e);
    } catch (NumberFormatException e) {
        throw new EmfRuntimeException(FAILED_TO_PARSE_DATE + isoDate, e);
    } catch (IllegalArgumentException e) {
        throw new EmfRuntimeException(FAILED_TO_PARSE_DATE + isoDate, e);
    }

    return parsed;
}

From source file:com.sirma.itt.emf.time.ISO8601DateFormat.java

/**
 * Parse date from ISO formatted string.
 * /* w w  w  .  j a v a  2  s.co m*/
 * @param isoDate
 *            ISO string to parse
 * @return the date
 */
public static Date parse(String isoDate) {
    if (StringUtils.isBlank(isoDate)) {
        return null;
    }
    Date parsed = null;

    try {
        int offset = 0;

        // extract year
        int year = Integer.parseInt(isoDate.substring(offset, offset += 4));
        if (isoDate.charAt(offset) != '-') {
            throw new IndexOutOfBoundsException("Expected - character but found " + isoDate.charAt(offset));
        }

        // extract month
        int month = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != '-') {
            throw new IndexOutOfBoundsException("Expected - character but found " + isoDate.charAt(offset));
        }

        // extract day
        int day = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != 'T') {
            throw new IndexOutOfBoundsException("Expected T character but found " + isoDate.charAt(offset));
        }

        // extract hours, minutes, seconds and milliseconds
        int hour = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != ':') {
            throw new IndexOutOfBoundsException("Expected : character but found " + isoDate.charAt(offset));
        }
        int minutes = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        if (isoDate.charAt(offset) != ':') {
            throw new IndexOutOfBoundsException("Expected : character but found " + isoDate.charAt(offset));
        }
        int seconds = Integer.parseInt(isoDate.substring(offset += 1, offset += 2));
        int milliseconds = 0;
        if (isoDate.charAt(offset) == '.') {
            // ALF-3803 bug fix, milliseconds are optional
            milliseconds = Integer.parseInt(isoDate.substring(offset += 1, offset += 3));
        }

        // extract timezone
        String timezoneId;
        char timezoneIndicator = isoDate.charAt(offset);
        if ((timezoneIndicator == '+') || (timezoneIndicator == '-')) {
            timezoneId = "GMT" + isoDate.substring(offset);
        } else if (timezoneIndicator == 'Z') {
            timezoneId = "GMT";
        } else {
            throw new IndexOutOfBoundsException("Invalid time zone indicator " + timezoneIndicator);
        }

        // Get the timezone
        Map<String, TimeZone> timezoneMap = timezones.get();
        if (timezoneMap == null) {
            timezoneMap = new HashMap<>(3);
            timezones.set(timezoneMap);
        }
        TimeZone timezone = timezoneMap.get(timezoneId);
        if (timezone == null) {
            timezone = TimeZone.getTimeZone(timezoneId);
            timezoneMap.put(timezoneId, timezone);
        }
        if (!timezone.getID().equals(timezoneId)) {
            throw new IndexOutOfBoundsException();
        }

        // initialize Calendar object#
        // Note: always de-serialise from Gregorian Calendar
        Calendar calendar = new GregorianCalendar(timezone);
        calendar.setLenient(false);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, milliseconds);

        // extract the date
        parsed = calendar.getTime();
    } catch (IndexOutOfBoundsException e) {
        throw new EmfRuntimeException("Failed to parse date " + isoDate, e);
    } catch (NumberFormatException e) {
        throw new EmfRuntimeException("Failed to parse date " + isoDate, e);
    } catch (IllegalArgumentException e) {
        throw new EmfRuntimeException("Failed to parse date " + isoDate, e);
    }

    return parsed;
}

From source file:net.mumie.coursecreator.graph.MetaInfos.java

public static Calendar newCalendar(long millis) {
    Calendar cal = Calendar.getInstance();
    cal.setLenient(true);
    cal.setTimeInMillis(millis);//from  w  w w  .ja va2s  .  c  o  m
    return cal;
}

From source file:org.openmrs.module.distrotools.test.TestUtils.java

/**
 * Convenience method to create a new date with time
 * @param year the year/*from ww w  . j  av  a2 s.com*/
 * @param month the month
 * @param day the day
 * @param hour the hour
 * @param minute the minute
 * @param second the second
 * @return the date
 * @throws IllegalArgumentException if date values are not valid
 */
public static Date date(int year, int month, int day, int hour, int minute, int second) {
    Calendar cal = new GregorianCalendar(year, month - 1, day, hour, minute, second);
    cal.setLenient(false);
    return cal.getTime();
}

From source file:com.clustercontrol.calendar.util.CalendarValidator.java

/**
 * YMD//from w w  w .j  a  v  a  2 s  . com
 * YearMonthDay??
 * @param ymd
 * @throws InvalidSetting
 */
public static void validateYMD(YMD ymd) throws InvalidSetting {
    Integer year = ymd.getYear();
    Integer month = ymd.getMonth();
    Integer day = ymd.getDay();

    if (year == null) {
        String[] args = { "(" + MessageConstant.YEAR.getMessage() + ")" };
        m_log.warn("validateYMD year=null");
        throw new InvalidSetting(MessageConstant.MESSAGE_PLEASE_SET_CALENDAR_PATTERN.getMessage(args));
    }
    if (month == null || month <= 0) {
        String[] args = { "(" + MessageConstant.MONTH.getMessage() + ")" };
        m_log.warn("validateYMD month=null");
        throw new InvalidSetting(MessageConstant.MESSAGE_PLEASE_SET_CALENDAR_PATTERN.getMessage(args));
    }
    if (day == null || day <= 0) {
        String[] args = { "(" + MessageConstant.DAY.getMessage() + ")" };
        m_log.warn("validateYMD day + month");
        throw new InvalidSetting(MessageConstant.MESSAGE_PLEASE_SET_CALENDAR_PATTERN.getMessage(args));
    }
    //???
    boolean ret = false;
    Calendar cal = HinemosTime.getCalendarInstance();
    cal.setLenient(true);
    cal.set(year, month - 1, day);
    if (cal.get(Calendar.MONTH) != (month - 1) % 12) {
        // error
        m_log.warn("year=" + year + ",month=" + month + ",day=" + day + ",ret=" + ret);
        String[] args = { year + "/" + month + "/" + day };
        throw new InvalidSetting(MessageConstant.MESSAGE_SCHEDULE_NOT_EXIST.getMessage(args));
    }
    m_log.debug("year=" + year + ",month=" + month + ",day=" + day + ",ret=" + ret);
}

From source file:com.silverpeas.jcrutil.RandomGenerator.java

public static Calendar getFuturCalendar() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, 1 + random.nextInt(10));
    calendar.set(Calendar.HOUR_OF_DAY, getRandomHour());
    calendar.set(Calendar.MINUTE, getRandomMinutes());
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.setLenient(false);
    try {//from  w  ww.j  av  a2  s .  com
        calendar.getTime();
    } catch (IllegalArgumentException ie) {
        return getFuturCalendar();
    }
    return calendar;
}