This post will discuss how to convert a date string to a date object in Java.

In the previous post, we have seen how to use the java.util.SimpleDateFormat class to format and parsing dates in Java. This post will discuss how to do the same in Java using the java.time package. There were many flaws in the design and implementation of Java date and time classes. Programmers preferred the Joda-Time library before Java SE 8, which provided a quality replacement for the Java date and time classes. Therefore, Java 8 introduced many new sets of classes that were inspired by the Joda-Time library.

1. Using Instant.parse() method

The 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. For example, if the date string is in valid ISO 8601 format of YYYY-MM-DDTHH:mm:ss.SSSZ, we can parse it using the Instant.parse() method like this:

Download  Run Code

Output:

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

2. Using DateTimeFormatter class

If date string is not in the ISO-8601 instant format, we can use DateTimeFormatter in Java 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 following example, we have used the LocalDate class to parse the date string, which is the standard class for representing a date without a time. We can also use the LocalDateTime class for representing date and time without a time zone, or the ZonedDateTime class for representing date and time with a time-zone. For example, if our date string is in the format of d MMMM, yyyy, we can create a formatter like this:

Download  Run Code

That’s all about converting a date string to a date object in Java.