Java’s standard class for representing dates and times is called java.util.Date, and it may be used to turn a string representation of a date and time, such as “2022-01-01,” into a date.
When you have a string representation of a date and need to manipulate it, such as compare it to another date or format it for display, this conversion is helpful. The string in the data format includes a task for converting the string into the actual data. This concept uses the parse() method that will help in converting string to date format in java. In this conversion, you can find that a specific data-time pattern is used for getting the input string. This will illustrate the data with the use of Instant, LocalDate and SimpleDateFormat classes.
How to convert string to date (java)
There are three approaches to convert a string to a date in Java:
- Using SimpleDateFormat: The most popular method in Java for converting a string to a date is to use the SimpleDateFormat class. It includes use of date patterns, such as “yyyy-MM-dd,” which can be used to describe the format of the string representation. This parse method of the SimpleDateFormat class can be used for converting the string to a java.util.Date object. This approach allows defining the time pattern and date pattern strings for the data and time format and this uses pattern letters. It includes the use of count for determining the representation of time and data. You can see that these patterns are case-sensitive and use patterns that are text-based that will be represented in full form.
- Using DateTimeFormatter: The new date and time API in Java includes the DateTimeFormatter class. It is considered a contemporary and effective method for formatting and parsing dates and timings is provided by this class. The use of the parse method with the string represents the date and the chosen format pattern that converts a string to a date using the DateTimeFormatter. This approach will include a way for converting string to custom date format with the use of date object. This approach is considered as the widespread operation in Java. It will help in providing the approach with a predefined formatter and this allows defining formatters for getting exact results in the right format.
- Using LocalDate and LocalDateTime: The new date and time API includes the LocalDate and LocalDateTime classes. It offers a more contemporary and effective method for representation of dates and times than java.util.Date and Calendar. You can use the parse method and the string representation of the date along with the required format pattern to convert a string to a LocalDate or LocalDateTime. This approach uses a parse method by taking two arguments. This approach includes arguments for representation of data by taking input as string. It uses the DateTime API that was introduced in Java 8 that makes the conversion easy and it includes instances with values classed like LocalTime and LocalDate.
Let’s look at examples of each approach for getting a clear understanding of every approaches for converting a string to a date in Java:
Approach 1: Convert String to date Using SimpleDateFormat
Here is an example of how you can convert a string to a java.util.Date object using the SimpleDateFormat class in Java:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample {
public static void main(String[] args) {
// Date string in the format of "yyyy-MM-dd"
String dateString = "2022-01-01";
// Create a SimpleDateFormat object to specify the format of the date string
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
// Use the formatter to parse the date string into a Date object
Date date = formatter.parse(dateString);
// Print the parsed date
System.out.println("Date: " + date);
}
catch (ParseException e) {
// If the date string can't be parsed, print an error message
System.out.println("Unable to parse the date: " + e.getMessage());
}
}
}
Output:
Date: Sun Jan 01 00:00:00 EST 2022
Explanation of code:
- We first create a string representation of the date, dateString
- We create a SimpleDateFormat object, formatter, that uses the pattern “yyyy-MM-dd” to format and parse the date string.
- The parse method of the formatter object is then used to convert the string to a java.util.Date object. T
- The date is then printed to the console. Note that the parse method can throw a ParseException if it is unable to parse the string into a date, so we include a try-catch block to handle this exception.
Approach 2: Convert String to date Using DateTimeFormatter
It is an example of how you can convert a string to a java.time.LocalDate object using the DateTimeFormatter class in Java 8 and later:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class StringToDateExample {
public static void main(String[] args) {
// Date string in the format of "yyyy-MM-dd"
String dateString = "2022-01-01";
// Create a DateTimeFormatter object to specify the format of the date string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Use the formatter to parse the date string into a LocalDate object
LocalDate date = LocalDate.parse(dateString, formatter);
// Print the parsed date
System.out.println("Date: " + date);
}
}
Output:
Date: 2022-01-01
Explanation of code:
- We first create a string representation of the date, dateString.
- We create a DateTimeFormatter object, formatter, that uses the pattern “yyyy-MM-dd” to format and parse the date string.
- The parse method of the LocalDate class is then used to convert the string to a java.time.LocalDate object. The date is then printed to the console.
Approach 3: Convert Str to date Using LocalDate and LocalDateTime
This is an example of how you can convert a string to a java.time.LocalDateTime object using the LocalDateTime class in Java 8 and later:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class StringToDateExample {
public static void main(String[] args) {
// Date and time string in the format of "yyyy-MM-dd'T'HH:mm:ss"
String dateString = "2022-01-01T10:00:00";
// Create a DateTimeFormatter object to specify the format of the date and time string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
// Use the formatter to parse the date and time string into a LocalDateTime object
LocalDateTime date = LocalDateTime.parse(dateString, formatter);
// Print the parsed date and time
System.out.println("Date: " + date);
}
}
Output:
Date: 2022-01-01T10:00:00
Explanation of code:
- We first create a string representation of the date, dateString.
- We create a DateTimeFormatter object, formatter, that uses a specific pattern to format and parse the date string.
- The parse method of the LocalDate or LocalDateTime class is then used to convert the string to a java.time.LocalDate or java.time.LocalDateTime object, respectively. The date is then printed to the console.
Best approach for converting string to date in Java
The DateTimeFormatter class in Java is the recommended approach for converting strings to dates because it provides a thread-safe, flexible, and easy-to-use solution for parsing and formatting dates and times. It includes following advantages:
- It provides several built-in formats, as well as the ability to define custom formats, which makes it well-suited for handling a wide range of date and time formats.
- DateTimeFormatter is part of the new java.time package introduced in Java 8, which provides a modern, type-safe, and easy-to-use API for handling dates and times.
- The SimpleDateFormat class is part of the older java.util package and is not thread-safe, meaning it cannot be used safely in multi-threaded applications without adding extra synchronization. SimpleDateFormat also requires manual handling of time zones, which can lead to problems with date and time calculations.
In summary, DateTimeFormatter is the preferred approach for converting strings to dates in Java due to its improved thread safety, flexibility, and ease of use.
Sample Problem for converting string to date in Java
Sample Question 1
Write the code for displaying formatted data with the use of SimpleDateFormat class and display the output
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// Create a Date object
Date date = new Date();
// Create a SimpleDateFormat object with the desired format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
// Use the format method of SimpleDateFormat to format the date
String formattedDate = simpleDateFormat.format(date);
// Print the formatted date
System.out.println("Formatted date: " + formattedDate);
}
}
Output:
Formatted date: 08-02-2023
Sample Question 2
Write the code for demonstrating the usage of Java’s DateTimeFormatter class to format a date and time string representing the current date and time in the format dd-MM-yyyy HH:mm:ss.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Create a LocalDateTime object with the current date and time
LocalDateTime now = LocalDateTime.now();
// Define a DateTimeFormatter with the desired format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
// Use the format method of the DateTimeFormatter to format the date and time string
String formattedDateTime = now.format(formatter);
// Print the formatted date and time string
System.out.println("Formatted date and time: " + formattedDateTime);
}
}
Output:
Formatted date and time: 08-02-2023 12:34:56
Sample Question 3
Write the code for demonstrating the usage of Java’s LocalDate class to format a date string
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Create a LocalDate object with the current date
LocalDate today = LocalDate.now();
// Define a DateTimeFormatter with the desired format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
// Use the format method of the DateTimeFormatter to format the date string
String formattedDate = today.format(formatter);
// Print the formatted date string
System.out.println("Formatted date: " + formattedDate);
}
}
Output:
Formatted date: 08-02-2023
Conclusion
Converting a string representation of a date to a java.util.Date object or java.time.LocalDate object in Java requires the use of a DateFormat or DateTimeFormatter object, respectively.We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.