将身份证号中的出生日期转换成Date对象并按yyyy年MM月dd日格式输出

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;


public class IdNo {
     
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
    static Date idNo(String id){
     
        String regex = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$";
        Date date=new Date();
        if(id.matches(regex)){
     
            String y=id.substring(6,10);
            String m=id.substring(10,12);
            String d=id.substring(12,14);
            try {
     
                date=sdf.parse(y+"年"+m+"月"+d+"日");
            } catch (ParseException e) {
     
                e.printStackTrace();
            }
        }
        return date;
    }
    public static void main(String[] args) {
     

        Scanner input = new Scanner(System.in);
        String id=input.next();

        String birth = sdf.format(idNo(id));
        System.out.println(birth);

    }
}

在这里插入图片描述

你可能感兴趣的:(学习笔记,java,date)