0

I have a date time string like this: Java Code:

String datetimeString = "Tue Apr 10 15:19:06 CEST 2018";

I would like to convert this to a date like this: 2018-04-10 How can I do this? I have tried this:

Date result;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
result = formatter.parse (datetimeString);

But I get "Unparseable date"

iabu
  • 1
  • 5
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jan 13 '20 at 05:21

1 Answers1

2

Well since you already applied the brute force method, here's how to use the API.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class DateTest {


   public static void main(String[] args) throws Exception {
      String datetimeString = "Tue Apr 10 15:19:06 CEST 2018";

      String from_format = "E MMM dd HH:mm:ss z yyyy";
      String to_format = "yyyy-MM-dd";

      DateTimeFormatter from_formatter = DateTimeFormatter.ofPattern(from_format);
      DateTimeFormatter to_formatter = DateTimeFormatter.ofPattern(to_format);

      LocalDateTime ldt = LocalDateTime.parse(datetimeString, from_formatter);

      System.out.println(ldt.format(to_formatter));
   }
}

In the DateTimeFormatter class it is important to understand the format symbol AND the presentation descriptions for proper symbol count.

Marius Jaraminas
  • 813
  • 1
  • 7
  • 19
Faid
  • 554
  • 1
  • 5
  • 18
  • 1
    Note that `to_formatter` is not actually necessary, since [LocalDate.toString() is guaranteed to return a string in that format](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/time/LocalDate.html#toString%28%29). – VGR Jan 12 '20 at 23:37