EN
Java - convert String to Date
13
points
In Java, we can convert String to Date in couple of different ways.
Short solutions:
// solution 1
Date date1 = new SimpleDateFormat("dd/MM/yyyy").parse("24/12/2018");
// result:
// Mon Dec 24 00:00:00 CET 2018
// solution 2
Date date2 = Date.from(LocalDate.parse("24/12/2018", DateTimeFormatter
.ofPattern("dd/MM/yyyy")).atStartOfDay(ZoneId.systemDefault())
.toInstant());
// result:
// Mon Dec 24 00:00:00 CET 2018
1. Using SimpleDateFormat
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Example1 {
public static void main(String[] args) throws ParseException {
String strDate = "24/12/2018";
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(strDate);
System.out.println(date); // Mon Dec 24 00:00:00 CET 2018
}
}
Output:
Mon Dec 24 00:00:00 CET 2018
2. Using DateTimeFormatter and LocalDate
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Example2 {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String strDate = "24/12/2018";
LocalDate localDate = LocalDate.parse(strDate, formatter);
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault())
.toInstant());
System.out.println(date); // Mon Dec 24 00:00:00 CET 2018
}
}
Output:
Mon Dec 24 00:00:00 CET 2018
Post summary image