-1

I‘m fetching dates which have the format yyyy-MM-dd. I have these extracted as a string which would look like this:

String date = "2020-09-05";

Now I want to convert it into a EEE, d MMM yyyy format, so the result should be: Sat, 5 Sep 2020. I tried reformatting it like this:

Date convertedDate = new SimpleDateFormat(EEE, d MMM yyyy).parse(date);

For some reason this and many tries to get around it all end up with a java.text.ParseException: Unparseable date "2020-09-05".

Can‘t I convert a date from a string like that? Is there a better way to reformat a string into other formats?

user9582784
  • 175
  • 1
  • 8
  • 2
    The code you’ve posted is invalid Java. Please double-check what you’ve written. – Konrad Rudolph Sep 05 '20 at 16:46
  • 1
    Try first parsing the date in its existing format, then outputting the date _that you parsed it into_ in the format you want. Internally, the data structure always formats its data the same way, and you don't know what that way is - it only matters when you tell the data structure to output its data in a specific form. – Green Cloak Guy Sep 05 '20 at 16:46
  • 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 `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 05 '20 at 17:03

3 Answers3

3

You need to make a distinction between parsing the date (turning a String into a Date or LocalDate class) and formatting a date (turning the Date or LocalDate class instance to a String).

To parse the initial string, use:

LocalDate convertedDate = LocalDate.parse(date)

To format the convertedDate, use:

String formattedDate = convertedDate.format(DateTimeFormatter.ofPattern("EEE, d MMM yyyy"))

EDIT: I am assuming you are at least on Java 8, so you can use the newer date/time classes. See https://www.baeldung.com/java-8-date-time-intro for some more info.

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
1

You are mixing up parsing and formatting: your code is trying to parse a string given the format. You’re telling Java you’re expecting the date to contain the week name.

You need to first parse your date in the format it’s in. This will give you a date. You next need format your date with the desired format, which will give you a string:

final String dateString = "2020-09-05";
final Date date = new SimpleDateFormat("y-M-d").parse(dateString);
final String converted = new SimpleDateFormat("E, d MMM y").format(date);
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

ok here's the code:

String sDate1="1998-12-31";
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(sDate1);
 
        System.out.println("EEE, d MMM yyyy formatted date : " + new SimpleDateFormat("EEE, d MMM yyyy").format(date));
majkl zumberi
  • 156
  • 1
  • 8