Example usage for java.text DateFormat setLenient

List of usage examples for java.text DateFormat setLenient

Introduction

In this page you can find the example usage for java.text DateFormat setLenient.

Prototype

public void setLenient(boolean lenient) 

Source Link

Document

Specify whether or not date/time parsing is to be lenient.

Usage

From source file:fr.paris.lutece.plugins.suggest.utils.SuggestUtils.java

/**
 * return a timestamp Object which correspond with the string specified in
 * parameter./*  w w  w . j av a  2s .  co  m*/
 * @param strDate the date who must convert
 * @param locale the locale
 * @return a timestamp Object which correspond with the string specified in
 *         parameter.
 */
public static Timestamp getFirstMinute(String strDate, Locale locale) {
    try {
        Date date;
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate.trim());

        Calendar caldate = new GregorianCalendar();
        caldate.setTime(date);
        caldate.set(Calendar.MILLISECOND, 0);
        caldate.set(Calendar.SECOND, 0);
        caldate.set(Calendar.HOUR_OF_DAY, caldate.getActualMinimum(Calendar.HOUR_OF_DAY));
        caldate.set(Calendar.MINUTE, caldate.getActualMinimum(Calendar.MINUTE));

        Timestamp timeStamp = new Timestamp(caldate.getTimeInMillis());

        return timeStamp;
    } catch (ParseException e) {
        return null;
    }
}

From source file:com.datatorrent.contrib.parser.FixedWidthParser.java

/**
 * Function to validate and set the current field.
 * @param currentField the field which is to be validated and set
 * @param value the parsed value of the field
 * @param typeInfo information about the field in POJO
 * @param pojoObject POJO which is to be set
 * @param toEmit the map to be emitted/*ww w .j  a va  2s.  co  m*/
 */
private void validateAndSetCurrentField(FixedWidthSchema.Field currentField, String value,
        FixedWidthParser.TypeInfo typeInfo, Object pojoObject, HashMap toEmit) {
    try {
        String fieldName = currentField.getName();
        if (value != null && !value.isEmpty()) {
            Object result;
            switch (currentField.getType()) {
            case INTEGER:
                result = Integer.parseInt(value);
                break;
            case DOUBLE:
                result = Double.parseDouble(value);
                break;
            case STRING:
                result = value;
                break;
            case CHARACTER:
                result = value.charAt(0);
                break;
            case FLOAT:
                result = Float.parseFloat(value);
                break;
            case LONG:
                result = Long.parseLong(value);
                break;
            case SHORT:
                result = Short.parseShort(value);
                break;
            case BOOLEAN:
                if (value.compareToIgnoreCase(currentField.getTrueValue()) == 0) {
                    result = Boolean.parseBoolean("true");
                } else if (value.compareToIgnoreCase(currentField.getFalseValue()) == 0) {
                    result = Boolean.parseBoolean("false");
                } else {
                    throw new NumberFormatException();
                }
                break;
            case DATE:
                DateFormat df = new SimpleDateFormat(currentField.getDateFormat());
                df.setLenient(false);
                result = df.parse(value);
                break;
            default:
                throw new RuntimeException("Invalid Type in Field", new Exception());
            }
            toEmit.put(fieldName, result);
            if (typeInfo != null && pojoObject != null) {
                typeInfo.setter.set(pojoObject, result);
            }
        } else {
            toEmit.put(fieldName, value);
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException("Error parsing" + value + " to Integer type", e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing" + value, e);
    } catch (Exception e) {
        throw new RuntimeException("Error setting " + value + " in the given class" + typeInfo.toString(), e);
    }
}

From source file:com.netflix.governator.lifecycle.LifecycleManager.java

private Date parseDate(String configurationName, String value, Configuration configuration) {
    DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
    formatter.setLenient(false);

    try {/*from www . j  a  v  a 2  s.c  om*/
        return formatter.parse(value);
    } catch (ParseException e) {
        // ignore as the fallback is the DatattypeConverter.
    }

    try {
        return DatatypeConverter.parseDateTime(value).getTime();
    } catch (IllegalArgumentException e) {
        ignoreTypeMismtachIfConfigured(configuration, configurationName, e);
    }

    return null;
}

From source file:fr.paris.lutece.plugins.document.service.docsearch.DocSearchService.java

/**
 * Format the date/*ww w  . j  a v  a 2 s  .  com*/
 * @param date the date
 * @return formatedDate the formated date
 */
private String formatDate(String date) {
    DateFormat dateFormat = new SimpleDateFormat(PATTERN_DATE, Locale.FRENCH);
    dateFormat.setLenient(false);

    Date formatedDate;

    try {
        formatedDate = dateFormat.parse(date.trim());
    } catch (ParseException e) {
        AppLogService.error(e);

        return null;
    }

    return dateFormat.format(formatedDate);
}

From source file:org.andromda.timetracker.web.timecardsearch.SearchTimecardsDetailsFormImpl.java

/**
 * Default constructor//  w w w  . ja va 2 s .  c o  m
 */
public SearchTimecardsDetailsFormImpl() {
    // - setup the default java.util.Date.toString() formatter
    final DateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
    dateFormatter.setLenient(true);
    this.dateTimeFormatters.put(null, dateFormatter);
}

From source file:com.examples.with.different.packagename.testcarver.DateTimeConverter.java

/**
 * Parse a String into a <code>Calendar</code> object
 * using the specified <code>DateFormat</code>.
 *
 * @param sourceType The type of the value being converted
 * @param targetType The type to convert the value to
 * @param value The String date value./* w w w. j a v a  2 s.c om*/
 * @param format The DateFormat to parse the String value.
 *
 * @return The converted Calendar object.
 * @throws ConversionException if the String cannot be converted.
 */
private Calendar parse(Class sourceType, Class targetType, String value, DateFormat format) {
    logFormat("Parsing", format);
    format.setLenient(false);
    ParsePosition pos = new ParsePosition(0);
    Date parsedDate = format.parse(value, pos); // ignore the result (use the Calendar)
    if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedDate == null) {
        String msg = "Error converting '" + toString(sourceType) + "' to '" + toString(targetType) + "'";
        if (format instanceof SimpleDateFormat) {
            msg += " using pattern '" + ((SimpleDateFormat) format).toPattern() + "'";
        }
        throw new ConversionException(msg);
    }
    Calendar calendar = format.getCalendar();
    return calendar;
}

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

private void computeFormats() {
    /*/* ww  w.  j  av a 2  s  . c  o m*/
     * The expander takes pattern strings (and expands them) or takes
     * already created DateFormat instances and keeps them in the correct
     * order with the expanded strings.
     */
    final LenientDateTimeParserExpander expander = new LenientDateTimeParserExpander(false, locale);

    /*
     * Fill in the default locale date time formats. The indexes (0,1,2,3)
     * correspond to SimpleDateFormat.FULL, LONG, MEDIUM, and SHORT. We go
     * from FULL (0) to MEDIUM (2) with dates to prevent 2-digit date
     * matching (matches way too early). We go from FULL (0) to SHORT (3)
     * with times.
     *
     * Using the integers directly is a hack, but this whole parser is a
     * hack, so I don't feel too bad.
     */
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 3; j++) {
            final DateFormat df = SimpleDateFormat.getDateTimeInstance(i, j, locale);
            df.setLenient(false);
            expander.add(df, true, true);
        }
    }

    /*
     * We can detect whether this parser's configured locale likes day
     * before month or month before day in its strings by instantiating a
     * short date formatter, passing a different month and day, and seeing
     * which appears first. We use the short date formatter so we don't get
     * (possibly localized) month names.
     */

    final Calendar c = new GregorianCalendar(timeZone, locale);
    c.clear();
    c.set(Calendar.MONTH, Calendar.JANUARY);
    c.set(Calendar.DATE, 5);
    c.set(Calendar.YEAR, 9999);
    final String defaultFormattedDate = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale)
            .format(c.getTime());

    final int monthIndex = defaultFormattedDate.indexOf("1"); //$NON-NLS-1$
    final int dateIndex = defaultFormattedDate.indexOf("5"); //$NON-NLS-1$

    // ISO goes next.
    expander.addExpanded(isoDateTimeFormats);

    if (dateIndex > monthIndex) {
        /*
         * Month-before-day. Use US before EU.
         */
        expander.addExpanded(usDateFormats);
        expander.addExpanded(euDateFormats);
    } else {
        /*
         * Day-before-month. Use EU before US.
         */
        expander.addExpanded(euDateFormats);
        expander.addExpanded(usDateFormats);
    }

    // Add just the default local date instances.
    for (int i = 0; i <= 2; i++) {
        final DateFormat df = SimpleDateFormat.getDateInstance(i, locale);
        df.setLenient(false);
        expander.add(df, true, false);
    }

    // Add just the default local time instances.
    for (int i = 0; i <= 3; i++) {
        final DateFormat df = SimpleDateFormat.getTimeInstance(i, locale);
        df.setLenient(false);
        expander.add(df, false, true);
    }

    // Generic time goes last.
    expander.addExpanded(genericTimeFormats);

    expandedFormats = expander.getSortedResults();
}

From source file:org.olat.core.util.Formatter.java

License:asdf

/**
 * formats the given date so it is friendly to read
 * /*  ww w . j  a  v a  2s . c  o  m*/
 * @param d the date
 * @return a String with the formatted date
 */
public String formatDate(Date d) {
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    df.setLenient(false);
    String da = df.format(d);
    return da;
}

From source file:org.olat.core.util.Formatter.java

License:asdf

/**
 * formats the given time period so it is friendly to read
 * /*  w w  w .  j av  a2  s . c om*/
 * @param d the date
 * @return a String with the formatted time
 */
public String formatTimeShort(Date d) {
    DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    df.setLenient(false);
    String da = df.format(d);
    return da;
}

From source file:org.olat.core.util.Formatter.java

License:asdf

/**
 * formats the given time period so it is friendly to read
 * /*ww w.  j  av  a2  s.co m*/
 * @param d the date
 * @return a String with the formatted time
 */
public String formatTime(Date d) {
    DateFormat df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
    df.setLenient(false);
    String da = df.format(d);
    return da;
}