DateTimeFormatter Support for Single Digit Day of Month and Month of Year

后端 未结 2 1415
無奈伤痛
無奈伤痛 2020-12-13 16:59

DateTimeFormmater doesn\'t seem to handle single digit day of the month:

String format = \"MM/dd/yyyy\";
String date   = \"5/3/1969\";
System.ou         


        
2条回答
  •  青春惊慌失措
    2020-12-13 17:39

    In Java 8 Date Time API, I recently used

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendOptional(DateTimeFormatter.ofPattern("M/dd/yyyy"))
                .appendOptional(DateTimeFormatter.ofPattern(("MM/dd/yyyy")))
                .toFormatter();
    
    System.out.println(LocalDate.parse("10/22/2020", formatter));
    System.out.println(LocalDate.parse("2/21/2020", formatter));
    

提交回复
热议问题