`

自定义日期和字符串之间的类型转换器另附把字符串解析成日期的方法

阅读更多
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

public class DateTypeConverter extends DefaultTypeConverter {
	@Override
	public Object convertValue(Map<String, Object> context, Object value,Class toType) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		//format.setLenient(false);	//设置输入的字符串形式必须符合此对象的格式化方法使用的形式
		try {
			if(toType == Date.class) {		//当字符串向Date类型转换时
				String[] params = (String[]) value;	//request.getParameterValues()
				return dateFormat.parse(params[0]);
			} else if(toType == String.class) {	//当Date转换成字符串时
				Date date = (Date) value;
				return dateFormat.format(date);
			}
		} catch (ParseException e) {}
		return null;
	}
}



把字符串解析成日期如下:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

public class Demo {

	public static void main(String[] args) {
		String strdate = "1990-12-32";
		
		/*SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		format.setLenient(false);
		try {
			Date date = format.parse(strdate);
			String localdate = format.format(date);
			System.out.println(localdate);
		} catch (ParseException e) {
			System.out.println("格式不对");
		}*/
		
		//用这个类转换12-32时就会抛异常
		DateLocaleConverter dcl = new DateLocaleConverter();
		
		try {
			dcl.convert(strdate, "yyyy-MM-dd");
		} catch (Exception e) {
			System.out.println("格式不对");
		}
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics