Java 8 DateTimeFormatter

user1111880 picture user1111880 · Feb 11, 2017 · Viewed 11k times · Source

I need to replace SimpleDataFormat with Java 8 DateTimeFormatter. Below is the code with SimpleDateFormat.

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(source);

Now I need to change it to DateTimeFormatter. I tried as below

LocalDateTime ld = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Date startdate = dtf.parse(dtf);

Now this is generating exception.

Answer

Sasi Kathimanda picture Sasi Kathimanda · Feb 11, 2017
   DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
   LocalDate localDate = LocalDate.parse("2017-02-11", dtf);
   System.out.println(localDate.toString());

if you want Date object from LocalDate,the following works

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

As @JonSkeet advised, If you're using Java 8 you should probably avoid java.util.Date altogether