java时间处理工具类总结三

package org.util.date;

import java.util.Date;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.lang.StringUtils;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import org.apache.commons.beanutils.Converter;

/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/

public class DateConverter implements Converter
{
    private DateFormat df = null;

    
/**
     * 根据日期格式构造
     */

    public DateConverter()
    {
        df = new SimpleDateFormat(
"yyyy-MM-dd");
    }
    public DateConverter(String format)
    {
        super();
        df = new SimpleDateFormat(format);
    }
    public Object convert(Class type, Object value)
    {
        if (value == null)
        {
            return null;
        }
        else if (type == Date.class)
        {
            return convertToDate(type, value);
        }
        else if (type == String.class)
        {
            return convertToString(type, value);
        }
        throw new ConversionException(
"Could not convert "
                                      + value.getClass().getName() +
" to " +
                                      type.getName());
    }

    protected Object convertToDate(Class type, Object value)
    {
        if (value instanceof String)
        {
            try
            {
                if (StringUtils.isEmpty(value.toString()))
                {
                    return null;
                }
                return df.parse((String) value);
            }
            catch (Exception pe)
            {
                throw new ConversionException(
"Error converting String to Date");
            }
        }
        throw new ConversionException(
"Could not convert "
                                      + value.getClass().getName() +
" to " +
                                      type.getName());
    }

    protected Object convertToString(Class type, Object value)
    {
        if (value instanceof Date)
        {
            try
            {
                return df.format(value);
            }
            catch (Exception e)
            {
                throw new ConversionException(
"Error converting Date to String");
            }
        }
        return value.toString();
    }
}

lunzi   2008-01-12 00:15:50 评论:0   阅读:582   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2004-2010 powered by YuLog