You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by "Bingel, Michael" <Mi...@paybox.net> on 2003/05/13 16:52:47 UTC

[beanutils] How to handle Date to String converter ?

Hi,

I need to format some Dates when they are copied to Strings 
using the BeanUtils.copyProperties().

Is it correct to register a Converter like this ?

  ConvertUtils.register (new DateConv(null), String.class);

Furthermore, how do I exit the Converter if the source 
class is not a Date and I don't want to handle the 
conversion ?


cheers   Mike



----- snip - some code to follow -----

package xxx;

import java.text.*;
import java.util.*;

import org.apache.commons.beanutils.*;
import org.apache.commons.beanutils.converters.*;


/**
 * <p>Standard {@link Converter} implementation that converts an incoming
 * String into a <code>java.util.Date</code> object, optionally using a
 * default value or throwing a {@link ConversionException} if a conversion
 * error occurs.</p>
 *
 * <p>Structure of this class ist taken from
 * <code>org.apache.commons.beanutils.converters.SqlDateConverter</code>
 * by Craig R. McClanahan</p>
 */

public final class DateConverter implements Converter {

    /**
     * Create a {@link Converter} that will throw a {@link
ConversionException}
     * if a conversion error occurs.
     */
    public DateConverter() {

        this.defaultValue = null;
        this.useDefault = false;

    }

    /**
     * Create a {@link Converter} that will return the specified default
value
     * if a conversion error occurs.
     *
     * @param defaultValue The default value to be returned
     */
    public DateConverter(Object defaultValue) {

        this.defaultValue = defaultValue;
        this.useDefault = true;

    }

    /**
     * Create a {@link Converter} that will return the specified default
value
     * if a conversion error occurs.
     *
     * @param defaultValue The default value to be returned
     * @param defaultFormat The default format to be returned
     */
    public DateConverter(Object defaultValue, String[] defaultFormat) {

        this.defaultFormat = defaultFormat;
        this.defaultValue = defaultValue;
        this.useDefault = true;

    }

    /**
     * The default value specified to our Constructor, if any.
     */
    private Object defaultValue = null;

    /**
     * Should we return the default value on conversion errors?
     */
    private boolean useDefault = true;

    /**
     * The default format specified to our Constructor, if any.
     */
    private String[] defaultFormat = {"yyyy-MM-dd HH:mm:ss", "dd.MM.yyyy
HH:mm:ss", "yyyy-MM-dd", "dd.MM.yyyy", "MM/dd/yyyy"};


    /**
     * Convert the specified input object into an output object of the
     * specified type.
     *
     * @param type Data type to which this value should be converted
     * @param value The input value to be converted
     *
     * @exception ConversionException if conversion cannot be performed
     *  successfully
     */
    public Object convert(Class type, Object value) {

        if (value == null) {
            if (useDefault) {
                return (defaultValue);
            } else {
                throw new ConversionException("No value specified");
            }
        }

// ===== start =====
        if ((value instanceof String) && ((type == Date.class)
                || type == java.sql.Timestamp.class)) { // String -> Date

            if (value == null || ((String)value).length() == 0) return null;
            for (int i = 0; i < defaultFormat.length; i++) {

                try {
                    SimpleDateFormat formatter = new
SimpleDateFormat(defaultFormat[i]);
                    return formatter.parse((String)value);
                } catch (ParseException pe) {
                    // if none of the conversion patterns worked
                    if (i == defaultFormat.length - 1) {
                        throw new ConversionException("Could not convert " +
(String)value + " to date: " + pe);
                    }
                }
            }

        } else if ((value instanceof Date) && (type == String.class)) { //
Date -> String

            SimpleDateFormat formatter = new
SimpleDateFormat(defaultFormat[0]);
            return formatter.format(value);

        } else if (type == String.class) {

            StringConverter sc = new StringConverter();
            return sc.convert(type, value);

        }
// ===== end =====

        if (value instanceof Date) {
            return (value);
        }

        try {

            SimpleDateFormat formatter = new
SimpleDateFormat(defaultFormat[0]);
            return formatter.parse(value.toString());

        } catch (Exception e) {
            if (useDefault) {
                return (defaultValue);
            } else {
                throw new ConversionException(e);
            }
        }

    }

}