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