LocalDate检验与转换

首先前置条件是:JDK8

  1. 字符串日期校验
public static void main(String[] args){
	// 定义校验格式,分别是:年月日、年月日时分秒
    public static final String PATTERN_YYYY_MM_DD_HH_MM_SS = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$";
    public static final String PATTERN_YYYY_MM_DD = "^\\d{4}-\\d{2}-\\d{2}$";
	
	String string = "2020-07-12";
	
	// 格式校验
	boolean pattern = Pattern.matches(PATTERN_YYYY_MM_DD, string);
}	
  1. 字符串日期与LocalDate、
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String s = df.format(localDate);
        System.out.println("LocalDateTime转成String类型的时间:"+s);
        
        LocalDate ldt = LocalDate.parse("2020-07-12",df);
        System.out.println("String类型的时间转成LocalDate:"+ldt);

        System.out.println("====");
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String localTime = dateTimeFormatter.format(localDateTime);
        System.out.println("LocalDateTime转成String类型的时间:"+localTime);
        
        LocalDateTime ldt1 = LocalDateTime.parse("2020-07-12 22:14:57",dateTimeFormatter);
        System.out.println("String类型的时间转成LocalDateTime:"+ldt1);
    }

你可能感兴趣的:(demo积累)