Convert String to Date in Java 8

In this post, we will see how to convert a String to Date in Java 8.


 

In the previous post, we have seen how to use java.util.SimpleDateFormat class for formatting and parsing dates in Java. In this post, we will see how to do the same in Java 8 using java.time package.

There were many flaws in design and implementation of Java date and time classes. Developers used to prefer Joda-Time library prior to Java SE 8, which provided a quality replacement for the Java date and time classes.

So Java 8 introduced many new set of classes which are inspired by Joda-Time.

 

1. Instant

java.time.Instant class is similar to java.util Date class but gives nanosecond accuracy. Instant.parse() method can be used to get an Instant instance from a string representing a valid instant in UTC. The string is parsed using DateTimeFormatter.ISO_INSTANT internally and can be displayed with a specified time zone as shown below:

 

Download   Run Code

Output:

2014-10-05T15:23:01Z
2014-10-05T10:23:01-05:00[America/Chicago]
2014-10-05T20:53:01+05:30[Asia/Kolkata]

 

2. DateTimeFormatter

We can use DateTimeFormatter in Java 8 to create a formatter object and pass this formatter to the parse method. We can define our own formatter or use predefined formatters provided by the DateTimeFormatter class.

In the example below, we have used LocalDate class to parse the date string, which is the standard class for representing a date without a time. We can also use java.time.LocalDateTime for representing date and time, and java.time.ZonedDateTime for representing date, and time with a time-zone.

 

Download   Run Code

Output:

2017-01-26

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz