How do I parse a text string into date and time?

In this code snippet example you will learn how to parse a text string into an instance of LocalDate, LocalTime and LocalDateTime. All of these classes provide a parse() method that accept an argument of text string that represent a valid date and time information and convert it into the corresponding object.

If the text string passed into the parse() method is not representing a valid date or time information this method throws a RuntimeException of type DateTimeParseException exception. If you want to handle this exception then you should wrap your code inside a try-catch block.

Let’s see the code snippet below as an example:

Running this code snippet will produce the following result:

As we can see from the output above, parsing a text string of "2014-02-31" give us a DateTimeParseException because the 31 of February is not a valid date.

How do I use java.time.LocalDateTime class?

The java.time.LocalDateTime class represents information of both date and time without time-zone. We can create LocalDateTime using the available static factory method such as the of() method or by combining an instance of LocalDate and LocalTime.

The following code snippet will show you both ways. First we begin with using the of() method where we can pass arguments such as the year, month, day, hour, minute and second. On the following line we also use the of() method but this time we pass an instance of LocalDate and LocalTime as the arguments.

We can also create an instance of LocalDateTime by using the LocalDate‘s atTime() method or LocalTime‘s atDate() method as seen in the code snippet above.

On the very end of the code snippet you can see how to obtain a LocalDate or LocalTime information from an instance of LocalDateTime using the toLocalDate() and toLocalTime() method.

Running this code snippet will give you the following result:

How do I use java.time.LocalTime class?

An instance of LocalTime class represent information about time. It doesn’t contains information about date. To create an instance of this class we can use the of() static factory method. There are two types of this method. The first one accept two arguments, hour and minute. The second type also accept the second as the arguments.

The code snippet below show you how to create an instance of LocalTime and how to obtains its values.

To get the values from the LocalTime object we can use the getHour(), getMinute() and getSecond() methods to get hour, minute and second respectively.

Running this snippet result the following output:

You can also use the get() method to read values represented by the LocalTime object. We call this method with the temporal field that we want to read. The following code snippet will give you the same result as the previous code, only this time we use the get() method.