Java 8 Parse String to Date

Let’s see how you can convert from string to date in java 8.

1) Convert string to date in ISO8601 format

By default, java dates are in ISO8601 format, so if you have any string which represent 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 !!

References:

DateTimeFormatter
LocalDateTime
LocalDate

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.