Friday, June 7, 2024

How to Convert String to LocalDate, LocalTime, LocalDateTime and ZonedDateTime in Java? Example Tutorial

The JDK 8 added a new Date and Time API (JSR 310) which introduces new date and time classes like LocalDateLocalTime, LocalDateTime, and ZonedDateTime. Now, if you have a String e.g. "2016-12-14 03:30" then how do parse it to LocalDate, LocalTime, LocalDateTime and ZonedDateTime? Similarly, if you have an instance of those classes how you can format to the String you want e.g. in dd/MM/yyyy format, or USA or UK format? Well, Java 8 provides a utility class called DateTimeFormatter which can be used to parse/format dates in Java 8. It also provides several built-in formatter e.g. ISO date format and other to facilitate formatting of dates to String.

 As compared to SimpleDateFormat of pre-Java8 world, DateTimeFormatter is both thread-safe, immutable and easy to use. You are also encouraged to store it on static constant for that reason. 

In this article, I'll show you how you can format/parse dates in Java 8 by converting String to LocalDate, LocalTime, LocalDateTime and ZonedDateTime classes. 

How to Convert String to LocalDate, LocalTime, LocalDateTime and ZonedDateTime in Java? Example Tutorial


How to Convert String to LocalDate, LocalTime, LocalDateTime and ZonedDateTime in Java

The article is divided into two parts, in the first part, you will learn the parsing of dates in Java 8, I mean converting String to various date classes like LocalDate, LocalTime, LocalDateTime, and ZonedDateTime. 

For example, how do you convert a String like "31-12-2024" to any date class, we will see that in this part and in the next part we will see exactly opposite, I mean formatting of dates or converting various date objects to formatted String in Java. 

In order to parse or format dates in Java one of the first thing you need is to define a DateTimeFormatter class which basically define date patterns like DDMMYYYY or DD-MM-YY, that's the link to convert any string to date and any date to formatted String. 

1. parsing String to LocalDate in Java. 

Just imaging that you are loading fixed deposit related data from a CSV file where one field is start_date and other is maturity_date, in order to store them into your Java program as object, you need to convert them into LocalDate object. 

LocalDate is generally used when you just have to store date information for example maturity_date which doesn't have any time information, birthday or expiry_day etc. 

Here are the steps to parse String to LocalDate in Java:

1. define a date format using DateTimeFormatter class

2. use the parse method of LocalDate to convert String to LocalDate

Here is the code example 

 // Define the date format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

        // String to be parsed
        String dateString = "08/06/2024";

        try {
            // Parse the String to a LocalDate
            LocalDate date = LocalDate.parse(dateString, formatter);
            System.out.println("Parsed date: " + date);
        } catch (DateTimeParseException e) {
            System.out.println("Invalid date format");
        }

Here the pattern is dd/MM/yyyy but it could be any other valid pattern. When you run this code, it will parse the String "31/12/2024" to a LocalDate object and print the parsed date. If the string does not match the format, it will catch the exception and print an error message.


2. parsing String to LocalTime

Now, let's see how to parse String to LocalTime in Java. The steps are exactly same, you define a formatter and then use the parse() method of the respective date time class like LocalTime in this case to convert String to LocalTime. Generally this object is used when you String only contains time information e.g. start_time or finish_time 

Here is a code example to show how to parse String to LocalTime in Java:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class StringToLocalTimeExample {
    public static void main(String[] args) {
        // Define the time format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

        // String to be parsed
        String timeString = "14:30:45";

        try {
            // Parse the String to a LocalTime
            LocalTime time = LocalTime.parse(timeString, formatter);
            System.out.println("Parsed time: " + time);
        } catch (DateTimeParseException e) {
            System.out.println("Invalid time format");
        }
    }
}

In this case, pattern is "HH:mm:ss" where HH is for two digit hour like 05 or 11, mm is two digit minutes like 05 and 59, and ss is two digit seconds like 04 and 58.

When you run this code, it will parse the String "14:30:45" to a LocalTime object and print the converted time. If the string does not match the format, it will catch the exception and print an error message.


3. parsing String to LocalDateTime

So far we have seen the example of parsing String to LocalDate and LocalTime in Java 8 and now we will see the example of parsing into LocalDateTime. You use this class when your String contains both date and time information like "31-12-2024 14:32:24". 

For conversion the steps are exactly the same, you first need to define a pattern for DateTimeFormatter class and then use the parse method of respective date class like LocalDateTime to convert String to date in Java 8. 

Here is a code example which you can run and play with to understand the process:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class StringToLocalDateTimeExample {
    public static void main(String[] args) {
        // Define the date and time format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

        // String to be parsed
        String dateTimeString = "08/06/2024 14:30:45";

        try {
            // Parse the String to a LocalDateTime
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            System.out.println("Parsed date and time: " + dateTime);
        } catch (DateTimeParseException e) {
            System.out.println("Invalid date and time format");
        }
    }
}


In this case, the pattern we have used is "dd/MM/yyyy HH:mm:ss"   which contains both date and time information. Another thing you need to keep in mind is to catch any parsing or formatting related information as dates can be wrongly stored in CSV file or any source systems. 

When you run this code, it will parse the text "08/06/2024 14:30:45" to a LocalDateTime object and print the converted date and time. If the string does not match the format, it will catch the exception and print an error message.


4. parsing String to ZonedDateTime

So far we have seen how to convert a formatted String to LocalDate, LocalTime, and LocalDateTime in Java 8 and now we will see one more date class from new Date and Time API, the ZonedDateTime, which not just contain date and time information but also time zone information. 

For example "08/06/2024 14:30:45 GMT", this is common on any application which deals with international user or data. 

Timezone is usually deonted by letter "z" in formatted String. 

The process to convert any String to ZonedDateTime is exactly same as before, you define a pattern and then use the parse() method of respective date and time class, ZonedDateTime in this case to convert the String to respective object. 

Now, let's see a code example:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class StringToZonedDateTimeExample {
    public static void main(String[] args) {
        // Define the date and time format with time zone
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z");

        // String to be parsed
        String zonedDateTimeString = "08/06/2024 14:30:45 UTC";

        try {
            // Parse the String to a ZonedDateTime
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(zonedDateTimeString, formatter);
            System.out.println("Parsed zoned date and time: " + zonedDateTime);
        } catch (DateTimeParseException e) {
            System.out.println("Invalid date and time format");
        }
    }
}

In this case our patter is  "dd/MM/yyyy HH:mm:ss z" which contains timezone information. 

When you run this code in your IDE or command line, it will parse the String "08/06/2024 14:30:45 UTC" to a ZonedDateTime object and print the parsed date, time, and time zone. If the string does not match the format, it will catch the exception and print an error message.


How to convert LocalDate, LocalTime, LocalDateTime, and ZoneDateTime to String in Java

Now that we have seen the parsing of dates in Java 8, I mean converting String to various date classes like LocalDate, LocalTime etc, now is the time to see the exactly opposite, I mean converting various date classes to String, also known as formatting of dates in Java. 

Formatting LocalDate in Java 8

In this part you already have LocalDate object but you want a formatted String to show to user or send in a JSON message to another system. In that case you can first create a formatter with a pattern you want and then you can use the format() method of respective classes to convert date objects to String in Java. 

The process is exactly same as parsing but instead of using the parse() method you will use the format() method of respective date and time classes:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateFormattingExample {
    public static void main(String[] args) {
        // Create a LocalDate instance
        LocalDate date = LocalDate.of(2024, 6, 8);

        // Define the date format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

        // Format the LocalDate to a String
        String formattedDate = date.format(formatter);

        // Print the formatted date
        System.out.println("Formatted date: " + formattedDate);
    }
}

In this case our pattern is "dd/MM/yyyy"  and when you run this code, it will create a LocalDate object for June 8, 2024, format it according to the pattern dd/MM/yyyy, and print 08/06/2024.


Formatting LocalTime in Java 8

Now, let's see another example of formatting LocalTime in Java. This is the object which only contains time information, there is no date information on it. 

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeFormattingExample {
    public static void main(String[] args) {
        // Create a LocalTime instance
        LocalTime time = LocalTime.of(14, 30, 45);

        // Define the time format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

        // Format the LocalTime to a String
        String formattedTime = time.format(formatter);

        // Print the formatted time
        System.out.println("Formatted time: " + formattedTime);
    }
}

In this example, our pattern is "HH:mm:ss"    which is hour, minutes and seconds. When you run this code, it will create a LocalTime object for 14:30:45, format it according to the pattern HH:mm:ss, and print 14:30:45


Formatting LocalDateTime in Java 8

So far we have seen an example of converting both LocalDate and LocalTime object to String in Java, also known as formatting because we use a pattern when we convert date time object to String. Now is the time to convert for format LocalDateTime in Java 8. This object contains both date and time information. 

The steps are exactly the same, you first create a formatter with a pattern and then call the format method of respective date and time class by passing the formatter you have created as shown in following example. 

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeFormattingExample {
    public static void main(String[] args) {
        // Create a LocalDateTime instance
        LocalDateTime dateTime = LocalDateTime.of(2024, 6, 8, 14, 30, 45);

        // Define the date and time format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

        // Format the LocalDateTime to a String
        String formattedDateTime = dateTime.format(formatter);

        // Print the formatted date and time
        System.out.println("Formatted date and time: " + formattedDateTime);
    }
}

In this example, our pattern is  "dd/MM/yyyy HH:mm:ss" which contains both date and time information. When you run this code, it will create a LocalDateTime object for June 8, 2024, 14:30:45, format it according to the pattern dd/MM/yyyy HH:mm:ss, and print 08/06/2024 14:30:45.


Formatting ZonedDateTime in Java 8

Now the last example of this article where we will convert ZonedDateTime  to String in Java. Since this class contains time zone information the pattern we will use also need to have timezone component and consequently the String generated will also have time zone information. 

Steps are exactly same, just create a formatter with correct pattern and then call the format() method of ZonedDateTime class by passing the formatter and the object you want to convert to String

Here is the code example you can use to understand the concept and process

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class ZonedDateTimeFormattingExample {
    public static void main(String[] args) {
        // Create a ZonedDateTime instance
        ZonedDateTime zonedDateTime = ZonedDateTime.now();

        // Define the date and time format with time zone
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z");

        // Format the ZonedDateTime to a String
        String formattedZonedDateTime = zonedDateTime.format(formatter);

        // Print the formatted date and time with time zone
        System.out.println("Formatted zoned date and time: " + formattedZonedDateTime);
    }
}

You can see that our pattern "dd/MM/yyyy HH:mm:ss z" has timzone component, denoted by small z.  When you run this code, it will create a ZonedDateTime object for the current date and time, format it according to the pattern dd/MM/yyyy HH:mm:ss z, and print something like 08/06/2024 14:30:45 UTC, depending on the current date, time, and time zone.


Important points

1) LocalDate, LocalTime, LocalDateTime, and ZonedDateTime all has parse() method for parsing String to date in Java 8. 

2) The parse() method by default parse in ISO-8601 format, but you can provide a DateTimeFormatter of your preferred pattern to parse String to date. 

3) Unlike SimpleDateFormat class, the DateTimeFormatter is both thread-safe and Immutable, hence you can also store it as static constants and can share among threads. 

4) The LocalDate is date without time, local means any locality e.g. "2016-12-14" 

5) The LocalTime is time without any date information e.g. "03:30"

6) The LocalDateTime contains both date and time information e.g. "2016-12-14 03:30" without any time zone information e.g. you just say that new year arrives at "2017-01-01 00:00".

7) The ZonedDateTime contains date, time as well as timezone information e.g. "2016-12-14 03:30 IST"

That's all about how to format/parse dates in Java 8. You can use parse() method of LocalDate or LocalDateTime() to parse the String containing Date. It doesn't need a formatter if String is in ISO-8601 format, alternatively you an provide any formatter you wish. 

The introduction of DateTimeFormatter really made the parsing and formatting of dates in Java 8 super easy. There is no risk of thread-safety issue which was present in pre-Java8 world duce to bulky and errorprone SimpleDateFormat. 

The DateTimeFormatter clas is both thread-safe and Immutable, which means you can also store them into static constant and reuse it for parsing/formatting throughout application. It also provides several built-in formatter and ability to define your custom date format. 


1 comment:

Feel free to comment, ask questions if you have any doubt.