Java 日期格式转换

正则表达式

/**
 * 正则表达式数组
 */
//2017-09-12T00:00:00,//2017-01-05T00:00:00+08:00,   //2016-01-21T04:13:56.293Z

//2017-09-12T00:00:00,
String[] regexArray = {"^\\d{4}-\\d{1,2}-\\d{1,2}T(([0-1]{1}[0-9]{1})|([2]{1}[0-4]{1}))([:])(([0-5]{1}[0-9]{1}|[6]{1}[0]{1}))([:])((([0-5]{1}[0-9]{1}|[6]{1}[0]{1})))",
        //2018年07月25日
        "^\\d{4}[\u5e74]\\d{1,2}[\u6708]\\d{1,2}[\u65e5]$",
        //2015/1/14 00:00:00
        "^\\d{4}\\/\\d{1,2}\\/\\d{1,2}\\s*(([0-1]{1}[0-9]{1})|([2]{1}[0-4]{1}))([:])(([0-5]{1}[0-9]{1}|[6]{1}[0]{1}))([:])((([0-5]{1}[0-9]{1}|[6]{1}[0]{1})))"};

 

 

 

 

 

 

 

 

代码书写:

public String doFormat(String value, String to) {
    try {
        for (String regex : regexArray) {
            if (value.contains("T")){
                try {
                    Date parse = DateFormatUtils.ISO_DATETIME_FORMAT.parse(value);
                    String format = DateFormatUtils.format(parse, "yyyy-MM-dd HH:mm:ss");
                    return format;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (value.matches(regex)) {

                if(value.contains("年")&&value.contains("月")&&value.contains("日")){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    Date parse = sdf.parse(value);//转换为util.date
                    String formated = DateFormatUtils.format(parse, to);
                    return formated;
                }
                if (value.contains("/")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    Date parse = sdf.parse(value);//转换为util.date
                    String format = DateFormatUtils.format(parse, "yyyy-MM-dd HH:mm:ss");
                    return format;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date parse = sdf.parse(value);//转换为util.date
                String formated = DateFormatUtils.format(parse, to);
                return formated;
            }
        }
    } catch (ParseException e) {
        log.warn("格式化失败:{}", e);
        return value;
    }
    log.warn("没有匹配的表达式");
    return value;
}

你可能感兴趣的:(Java)