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:javadz.beanutils.converters.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  av a2s . c  o  m*/
 * @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() + "'";
        }
        if (log().isDebugEnabled()) {
            log().debug("    " + msg);
        }
        throw new ConversionException(msg);
    }
    Calendar calendar = format.getCalendar();
    return calendar;
}

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

License:asdf

/**
 * formats the given date so it is friendly to read
 * //from  ww w  .  j  ava  2 s  .  com
 * @param d the date
 * @return a String with the formatted date and time
 */
public String formatDateAndTime(Date d) {
    if (d == null)
        return null;
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
    df.setLenient(false);
    String da = df.format(d);
    return da;
}

From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java

/**
 * convert a localized value into its XML Schema datatype representation. If the value given cannot be parsed with
 * the locale in betterForm context the default locale (US) will be used as fallback. This can be convenient for
 * user-agents that do not pass a localized value back.
 *
 * @param value the value to convert// ww w . j a  v a  2s.  com
 * @return converted value that can be used to update instance data and match the Schema datatype lexical space
 * @throws java.text.ParseException in case the incoming string cannot be converted into a Schema datatype representation
 */
protected String delocaliseValue(String value) throws XFormsException, ParseException {
    if (value == null || value.equals("")) {
        return value;
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N).equals("true")) {
        Locale locale = (Locale) getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        XFormsProcessorImpl processor = this.model.getContainer().getProcessor();

        if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":float")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":decimal")
                || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":double")) {

            NumberFormat formatter = NumberFormat.getNumberInstance(locale);
            formatter.setMaximumFractionDigits(Double.SIZE);
            BigDecimal number;

            try {
                number = strictParse(value, locale);
            } catch (ParseException e) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (NumberFormatException nfe) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            } catch (InputMismatchException ime) {
                LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale);
                return value;
            }
            return number.toPlainString();
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":date")) {
            DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = df.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                df = new SimpleDateFormat("yyyy-MM-dd");
                df.setLenient(false);
                d = df.parse(value);
            }
            df = new SimpleDateFormat("yyyy-MM-dd");
            return df.format(d);
        } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":dateTime")) {
            String timezone = "";
            // int position = ;
            if (value.contains("GMT")) {
                timezone = value.substring(value.indexOf("GMT") + 3, value.length());
            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());

            } else if (value.contains("Z")) {
                timezone = "Z";
            }

            DateFormat sf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
            Date d = null;
            try {
                d = sf.parse(value);
            } catch (ParseException e) {
                //try the default locale - else fail with ParseException
                sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                d = null;
                d = sf.parse(value);
            }
            sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            String converted = sf.format(d);
            if (!timezone.equals("")) {
                return converted + timezone;
            }
            return converted;
        }
    }
    return value;
}

From source file:net.netheos.pcsapi.providers.googledrive.GoogleDrive.java

private CFile parseCFile(CPath parentPath, JSONObject json) {
    String dateStr = json.getString("modifiedDate");
    try {/*  w  ww  .j a v  a 2  s  .  c o  m*/
        CFile cFile;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
        format.setLenient(false);

        if (dateStr.endsWith("Z")) { // ISO8601 syntax
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
        }
        Date modified = format.parse(dateStr);
        if (MIME_TYPE_DIRECTORY.equals(json.getString("mimeType"))) {
            cFile = new CFolder(parentPath.add(json.getString("title")), modified, null); // metadata
        } else {
            long fileSize;
            if (json.has("fileSize")) {
                fileSize = json.getLong("fileSize");
            } else {
                // google apps files (application/vnd.google-apps.document, application/vnd.google-apps.spreadsheet, etc.)
                // do not publish any size (they can not be downloaded, only exported).
                fileSize = -1;
            }
            cFile = new CBlob(parentPath.add(json.getString("title")), fileSize, json.getString("mimeType"),
                    modified, null); // metadata
        }
        return cFile;

    } catch (ParseException ex) {
        throw new CStorageException("Can't parse date modified: " + dateStr + " (" + ex.getMessage() + ")", ex);
    }
}

From source file:com.stimulus.archiva.presentation.SearchBean.java

public void setAfter(String after) {
    logger.debug("setAfter() {sentafter='" + after + "'}");

    // see if a time was specified
    DateFormat format = DateUtil.getShortDateFormat(getLocale());
    format.setLenient(false);
    try {//from  w  w  w.ja  v a  2 s .c  o m
        if (after.length() > 0)
            search.setAfter(format.parse(after));
        else
            search.setAfter(null);
        return;
    } catch (Exception pe) {
        logger.debug("failed to parse date {sentafter='" + after + "'}");
    }
    // ok could not parse datetime, so now parse date only
    DateFormat format2 = DateUtil.getShortDateFormat(getLocale());
    format2.setLenient(false);
    try {
        if (after.length() > 0) {
            Date date = format2.parse(after);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.HOUR_OF_DAY, 1);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            search.setAfter(cal.getTime());
            return;
        } else
            search.setAfter(null);
    } catch (ParseException pe) {
        logger.debug("failed to parse date {sentafter='" + after + "'}");
    }
}

From source file:com.stimulus.archiva.presentation.SearchBean.java

public void setBefore(String before) {
    logger.debug("setBefore() {before='" + before + "'}");
    // see if a time was specified
    DateFormat format = DateUtil.getShortDateFormat(getLocale());
    format.setLenient(false);
    try {//from   ww w . j ava2  s .  c  o  m
        if (before.length() > 0)
            search.setBefore(format.parse(before));
        else
            search.setBefore(null);
        return;

    } catch (Exception pe) {
        logger.debug("failed to parse date {sentafter='" + before + "'}");
    }
    // ok could not parse datetime, so now parse date only
    DateFormat format2 = DateUtil.getShortDateFormat(getLocale());
    format2.setLenient(false);
    try {
        if (before.length() > 0) {
            Date date = format2.parse(before);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            search.setBefore(cal.getTime());
            return;
        } else
            search.setBefore(null);
    } catch (ParseException pe) {
        logger.debug("failed to parse date {sentbefore='" + before + "'}");
    }
}

From source file:com.alibaba.citrus.service.requestcontext.support.ValueListSupport.java

/**
 * ?<code>DateFormat</code>???
 *
 * @param format       <code>DateFormat</code>
 * @param defaultValue /*from   w w  w .  j  a v a2s . com*/
 * @return <code>java.util.Date</code>
 */
public Date getDateValue(DateFormat format, Date defaultValue) {
    String value = getStringValue();
    Date date = defaultValue;

    if (value != null) {
        try {
            format.setLenient(false);
            date = format.parse(value);
        } catch (ParseException e) {
            date = defaultValue;
        }
    }

    return date;
}

From source file:org.sakaiproject.calendar.impl.GenericCalendarImporter.java

private DateFormat time24HourFormatter() {
    DateFormat rv = new SimpleDateFormat("HH:mm");
    rv.setLenient(false);
    return rv;//  w  w w.  j a  v a 2 s .c  o m
}

From source file:org.sakaiproject.calendar.impl.GenericCalendarImporter.java

private DateFormat timeFormatter() {
    DateFormat rv = new SimpleDateFormat("hh:mm a");
    rv.setLenient(false);
    return rv;//  w w w.j  ava 2  s  .c o m
}

From source file:org.sakaiproject.calendar.impl.GenericCalendarImporter.java

private DateFormat time24HourFormatterWithSeconds() {
    DateFormat rv = new SimpleDateFormat("HH:mm:ss");
    rv.setLenient(false);
    return rv;//from w ww  .  j a v  a 2s .co  m
}