Sai A Sai A
Updated date Jul 23, 2023
In this blog, we will explore various methods to convert a string representation of date and time into a LocalDateTime array, adhering to a specific format. We present two different approaches. The first method utilizes the DateTimeFormatter and Stream API introduced in Java 8, while the second method employs the SimpleDateFormat class from the pre-Java 8 Date and Time API.

Introduction:

Working with dates and times is a common task in Java programming. There are scenarios where we need to convert a string representation of a date and time into a LocalDateTime array, following a specific format. In this blog, we will explore multiple methods to accomplish this conversion, providing examples, explanations, and sample outputs. 

Method 1: Using DateTimeFormatter and Stream API

The first method involves using the DateTimeFormatter class and the Stream API to convert the string into a LocalDateTime array.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.stream.Stream;

public class StringToLocalDateTimeConverter {
    public static LocalDateTime[] convertStringToArray(String dateString, String format) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return Stream.of(dateString.split(","))
                .map(str -> LocalDateTime.parse(str.trim(), formatter))
                .toArray(LocalDateTime[]::new);
    }

    public static void main(String[] args) {
        String dateString = "2023-07-19 10:30:00, 2023-07-19 14:45:00, 2023-07-19 18:20:00";
        String format = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime[] dateTimeArray = convertStringToArray(dateString, format);
        System.out.println(Arrays.toString(dateTimeArray));
    }
}

Output:

[2023-07-19T10:30, 2023-07-19T14:45, 2023-07-19T18:20]

In this method, we define a static method convertStringToArray, which takes two parameters: dateString, representing the input string containing date and time values separated by commas, and format, representing the pattern of the input string.

We create an instance of DateTimeFormatter using the provided format. Next, we split the input string using the comma as the delimiter and process each individual string using the Stream API. For each string, we trim it and parse it into a LocalDateTime object using the formatter. Finally, we collect the LocalDateTime objects into an array and return it.

In the main method, we provide a sample input string with three date and time values, along with the corresponding format. We call the convertStringToArray method to convert the string to a LocalDateTime array. Finally, we print the array to verify the output.

Method 2: Using SimpleDateFormat and ArrayList

The second method involves using the SimpleDateFormat class from the pre-Java 8 Date and Time API, along with an ArrayList to store the LocalDateTime objects.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class StringToLocalDateTimeConverter {
    public static LocalDateTime[] convertStringToArray(String dateString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        List<LocalDateTime> dateTimeList = new ArrayList<>();
        String[] dateStrings = dateString.split(",");
        for (String str : dateStrings) {
            try {
                dateTimeList.add(LocalDateTime.parse(str.trim(), sdf.toPattern()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return dateTimeList.toArray(new LocalDateTime[0]);
    }

    public static void main(String[] args) {
        String dateString = "2023-07-19 10:30:00, 2023-07-19 14:45:00, 2023-07-19 18:20:00";
        String format = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime[] dateTimeArray = convertStringToArray(dateString, format);
        System.out.println(Arrays.toString(dateTimeArray));
    }
}

Output:

[2023-07-19T10:30, 2023-07-19T14:45, 2023-07-19T18:20]

In this method, we create an instance of the SimpleDateFormat class using the provided format. We also initialize an ArrayList to store the LocalDateTime objects.

We split the input string into an array of date strings using the comma as the delimiter. For each date string, we trim it and attempt to parse it into a LocalDateTime object using the SimpleDateFormat's pattern. If successful, we add the LocalDateTime object to the list. If an exception occurs during parsing, we print the stack trace for debugging purposes.

Finally, we convert the ArrayList to an array of LocalDateTime objects and return it.

Conclusion:

In this blog, we explored two methods to convert a string representation of date and time into a LocalDateTime array in Java. The first method used DateTimeFormatter and Stream API, taking advantage of Java 8 features. The second method relied on the older SimpleDateFormat class and utilized an ArrayList. Both methods provided the desired output by parsing the string according to a specific format. 

Comments (0)

There are no comments. Be the first to comment!!!