java基础之时间转换

1.需求如下

用户输入12位时间(年月日时分),string类型:201809061015
1.1将此转换为:20180906.1015
1.2将此转换为:2018-09-06 10:15:00

2.寻找弱点

2.1思路

将time-string转换为Calendar;
设定SimpleDateFormat的格式;
利用SimpleDateFormat的format方法转换为需要的time-string。

2.2代码

2.1 将time-string转换为Calendar

//判断参数的时间类型后,返回参数的calendar
public static Calendar getCalendarByTimeStr(String timeStr) throws Exception{
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(getSimpleDateFormatPattern(timeStr));
    Date date = sdf.parse(timeStr);
    cal.setTime(date);
    return cal;
}

//设定
public static String getSimpleDateFormatPattern(String timeStr) throws Exception{
    String[] regexArray = {"[A-Za-z]{3} [A-Za-z]{3} \\d{1,2}.*",
            "[0-9]{1,4}/\\d{1,2}/\\d{1,2}-\\d{1,2}:\\d{1,2}",
            "[0-9]{1,4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}",
            "\\d{8}.\\d{4}",
            "\\d+"};
    //str:Fri Jul 27 07:15:46 CST 2018
    String[] simpleStrArray = {"EEE MMM dd HH:mm:ss zzz yyyy",
            "yyyy/MM/dd-HH:mm",
            "yyyy-MM-dd HH:mm:ss",
            "yyyyMMdd.HHmm",
            "yyyyMMddHHmm"};
    Pattern pattern = null;
    Matcher matcher = null;
    boolean rs = false;
    for(int i=0;i<regexArray.length;i++){
        pattern = Pattern.compile(regexArray[i]);  
        matcher = pattern.matcher(timeStr); 
        rs = matcher.matches();
        if(rs){
            return simpleStrArray[i];
        }
    }
    throw new Exception("抱歉,不支持的时间格式!time="+timeStr);
}

2.2 转换为想要的str

public static String setTimestrToDesiredTimeStr(String inputTimeStr) throws Exception {
        Calendar cal = getCalendarByTimeStr(inputTimeStr);
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String DesiredTimeStr = sdFormat.format(cal.getTime());
        System.out.println(DesiredTimeStr);
        SimpleDateFormat sdFormat1 = new SimpleDateFormat("yyyyMMdd.HHmm");
        String DesiredTimeStr1 = sdFormat1.format(cal.getTime());
        System.out.println(DesiredTimeStr1);
        return DesiredTimeStr;
    }

2.4 结果

public static void main(String[] args) throws Exception {
        setTimestrToDesiredTimeStr("201809061015");
    }

2018-09-06 10:15:00
20180906.1015

3.恩,这会心情没有丝毫波澜,难道早上吃多了?

猜你喜欢

转载自blog.csdn.net/qq_29778641/article/details/82490715
今日推荐