java.time
Java 8 and later include the java.time framework. This structure deprecates the old java.util.Date/.Calendar classes discussed in other answers here.
The java.time.format package and its java.time.format.DateTimeFormatter class use template codes similar to those discussed in the accepted answer from Ray Myers. Although they are similar, they vary a little. In particular, they are strict regarding the number of repeated characters. If you say MM , then the month should have a zero plus, otherwise you will get a DateTimeParseException . If the month number may or may not have a zero space, just use the single-character M
In this code example, notice how the month number of the input line has a zero space and the day number of the month does not. Both are handled by a single character pattern.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M/d/yyyy" ); LocalDate localDate = formatter.parse ( "01/2/2015" , LocalDate :: from );
Dump for the console.
System.out.println ( "localDate: " + localDate );
localDate: 2015-01-02
source share