Learn to convert a string to date in Java 8 using the new date time API classes such as LocalDate, LocalDateTime, ZonedDateTime and DateTimeFormatter.
1. Convert string to date in ISO8601 format
By default, java dates are in ISO8601 format, so if you have any string which represents a date in ISO8601 format, then you can use LocalDate.parse()
or LocalDateTime.parse()
methods directly.
String armisticeDate = "2016-04-04"; LocalDate aLD = LocalDate.parse(armisticeDate); System.out.println("Date: " + aLD); String armisticeDateTime = "2016-04-04T11:50"; LocalDateTime aLDT = LocalDateTime.parse(armisticeDateTime); System.out.println("Date/Time: " + aLDT); Output: Date: 2016-04-04 Date/Time: 2016-04-04T11:50
2. Convert string to date in custom formats
If you have dates in some custom format, then you need to put additional logic to handle formatting as well using DateTimeFormatter.ofPattern()
.
String anotherDate = "04 Apr 2016"; DateTimeFormatter df = DateTimeFormatter.ofPattern("dd MMM yyyy"); LocalDate random = LocalDate.parse(anotherDate, df); System.out.println(anotherDate + " parses as " + random);
Happy Learning !!
Leave a Reply