In this tutorial, we will see how to convert a String into Date in Java, for many developers this is still a challenge so we try to help in making it simple.
// String -> Date
SimpleDateFormat.parse(String);
// Date -> String
SimpleDateFormat.format(date);
// In Java 8, String -> Date
LocalDate localDate = LocalDate.parse(date, formatter);
// In Java 8, Date -> String
formatter.format(localDate) // DateTimeFormatter
Refer to the table below for Date Time letter Patterns :
| Letter | Description | Examples |
| y | Year | 2020 |
| M | Month in year | July, 07, 7 |
| d | Day in month | 1-31 |
| E | Day name in week | Friday, Sunday |
| a | Am/pm marker | AM, PM |
| H | Hour in day | 0-23 |
| h | Hour in am/pm | 1-12 |
| m | Minute in hour | 0-60 |
| s | Second in minute | 0-60 |
Examples
1. String = “7-Jun-2020” to Date “dd-MMM-yyyy”
package com.test.dates;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtility {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2020";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date)); // returns a String
} catch (ParseException e) {
e.printStackTrace();
}
}
}
OUTPUT
Sun Jun 07 00:00:00 IST 2020
07-Jun-2020
2. String = “07182020” to Date “MMddyyyy“
package com.test.dates;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtility {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("MMddyyyy");
String dateInString = "07182020";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date)); // returns a String
} catch (ParseException e) {
e.printStackTrace();
}
}
}
OUTPUT
Sat Jul 18 00:00:00 IST 2020
07182020
3. In JAVA 8 using LocalDate API, Convert String “dd/MM/yyyy” to LocalDate “dd/MM/yyyy“
package com.test.dates;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateJava8 {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
String date = "18/07/2020";
LocalDate localDate = LocalDate.parse(date, formatter);
System.out.println(localDate);
System.out.println(formatter.format(localDate));
}
}
OUTPUT
2020-07-18
18/07/2020
Summary
In this tutorial, we learnt how to convert String to Date in java using SimpleDateFormat and LocalDate of Java8.
Hope you liked it !