Example usage for java.text DateFormat parseObject

List of usage examples for java.text DateFormat parseObject

Introduction

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

Prototype

public Object parseObject(String source, ParsePosition pos) 

Source Link

Document

Parses text from a string to produce a Date.

Usage

From source file:javadz.beanutils.locale.converters.DateLocaleConverter.java

/**
 * Convert the specified locale-sensitive input object into an output object of the
 * specified type./*from  w  ww.j a v a 2s .  co  m*/
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 * @return the converted Date value
 *
 * @exception org.apache.commons.beanutils.ConversionException 
 * if conversion cannot be performed successfully
 * @throws ParseException if an error occurs parsing
 */
protected Object parse(Object value, String pattern) throws ParseException {

    // Handle Date
    if (value instanceof java.util.Date) {
        return value;
    }

    // Handle Calendar
    if (value instanceof java.util.Calendar) {
        return ((java.util.Calendar) value).getTime();
    }

    if (locPattern) {
        pattern = convertLocalizedPattern(pattern, locale);
    }

    // Create Formatter - use default if pattern is null
    DateFormat formatter = pattern == null ? DateFormat.getDateInstance(DateFormat.SHORT, locale)
            : new SimpleDateFormat(pattern, locale);
    formatter.setLenient(isLenient);

    // Parse the Date
    ParsePosition pos = new ParsePosition(0);
    String strValue = value.toString();
    Object parsedValue = formatter.parseObject(strValue, pos);
    if (pos.getErrorIndex() > -1) {
        throw new ConversionException("Error parsing date '" + value + "' at position=" + pos.getErrorIndex());
    }
    if (pos.getIndex() < strValue.length()) {
        throw new ConversionException(
                "Date '" + value + "' contains unparsed characters from position=" + pos.getIndex());
    }

    return parsedValue;
}