Convert String to Date in Java

Exercise:

Write a Java Program to convert string to date.

1.Convert using predefined formatter

Click Here to View the Solution!
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
 
public class TimeString {
        public static void main(String[] args) {
        // Format y-M-d or yyyy-MM-d
        String string = "2020-11-28";
   LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE);
        System.out.println(date);
    }
} 
Click Here to View the Output!
2020-11-28
Click Here to View the Explanation!
  • This program is used for changing a string into a date by using a predefined formatter.
  • A string variable ‘string’ is initialized as a date (2020-11-28). And a date variable that uses a parse function and a predefined formatter (ISO_DATE).
  • The parse function is a LocalDate function that is used to parse a given string by utilizing the given formatter. And the formatter, ISO_DATE is used to accept a date string in either of the following formats: 2020-11-28 or 2020-11-28+05:45’.
  • It is to be noted, that the predefined formatter, IOS_DATE, can be removed and the parse() function initialization can also be done in the following manner:

LocalDate date = LocalDate.parse(string, DateTimeFormatter);

2.Convert using pattern formatter

Click Here to View the Solution!
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
 
public class TimeString {
        public static void main(String[] args) {
        String string = "November 28, 2020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(string, formatter);
        System.out.println(date);
    }
}  
Click Here to View the Output!
2020-11-28
Click Here to View the Explanation!
  • This program is used to change a string to a date by using a pattern formatter.
  • Firstly, a string variable string is initialized that contains the date in the following format: November,28,2020.
  • Secondly, in view of the format of the string, MM dd yyyy, a DateTimeFormatter variable formatter is created that will hold the same pattern.
  • Thirdly, the parse function in the date variable will parse the date and obtain the object LocalDate.
  • Finally, the date will be printed using the println() method.