在JAVA程序中前台页面输入的日期是有限定的,要求为【2000/02/20】只有这种格式java本身才能将前台接收的数据转换为日期格式。为了让用户拥有更好的体验。一般会做格式转换。
//Converter里面两个泛型,第一个是源类型,第二个是宿类型(目标类型)
public class MyCoverter implements Converter<String , Date>{
@Override
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
上面代码实现了前台可以输入格式为【2000-02-20】的日期,但是不能输入格式为【2000/02/20】的日期了。于是想到可以通过正则表达来全面解决一下日期格式的转换。
public Date convert(String source) {
SimpleDateFormat sdf = getDataFormat(source);
try {
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
private SimpleDateFormat getDataFormat(String source) {
SimpleDateFormat sdf = new SimpleDateFormat();
if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$",source)){
sdf = new SimpleDateFormat("yyyy-MM-dd");
}else if(Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$",source)){
sdf = new SimpleDateFormat("yyyy/MM/dd");
}else if(Pattern.matches("^\\d{4}\\d{2}\\d{2}$",source)){
sdf = new SimpleDateFormat("yyyyMMdd");
}else {
//这里抛出一个异常,
throw new TypeMismatchException("",Date.class);
}
return sdf;
}