怎么把各种输入的日期格式转换成yyyy-MM-dd格式比如1999/10/10    1999 10 10    1999_10_10   19991010像这种格式的字符串转换成1999-10-10这种标准的日期格式

解决方案 »

  1.   

    写一个类型转化器比如struts2中
    package util;import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Map;import ognl.DefaultTypeConverter;public class DateConvert extends DefaultTypeConverter {  
    public Object convertValue(Map context, Object value, Class toType) {
    String [] type=new String []{"yyyy/MM/dd HH:mm:ss",
    "yyyy-MM-dd HH:mm:ss",
    "yyyy年MM月dd日 HH:mm:ss",
    "yyyy/MM/dd",
    "yyyy-MM-dd",
    "yyyy年MM月dd日"};

    try {
    //为空就什么也不干
    if(value==null){
    return null;
    }
    //字符串变时间
    if(toType==Date.class){
    String [] ss=(String[])value;
    String s=ss[0];
    for (int i = 0; i < type.length; i++) {
    try {
    return new SimpleDateFormat(type[i]).parse(s);
    } catch (Exception e) {
    }
    }
    }else{//时间变字符串
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
    }

    } catch (Exception e) {
    e.printStackTrace();
    }

    return super.convertValue(context, value, toType);
    }

    }如果没有使用struts的话,自己写个过滤器拦截,核心代码不变!
      

  2.   

    简单的说,先读取字符串,在使用正则表达式设置模式,再用format()方法转成为自己需要的格式
      

  3.   

    DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
    String newDateStr =  parser.parse(日期字符串);