I think your problem is the missing Locale
in your SimpleDateFormat
. If you don't explicitly set one, the code may use your default Locale
, which then might not be ENGLISH
but something else, which is likely to be on a computer located on the Philipines. It would try to parse the Philipine abbreviation for Tue, for example, and that leads to an unparseable String
.
Here is what worked on my computer (also not ENGLISH
) after having got the same Exception
as you:
String expiryDate = "Tue Sep 21 12:11:37 PHT 2021";
Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH)
.parse(expiryDate);
System.out.println(date.toString());
This gave the following output:
Tue Sep 21 06:11:37 CEST 2021
This worked with a pattern having just one E
as well.
Java 8 - 10 solution with java.time
:
This successfully runs on Java 8 and 10, but according to the answer by @ArvindKumarAvinash, this won't work in Java 11 and possibly the versions above due to the abbreviation of the time zone in the String expiryDate
.
You could do it like this in java.time
:
String expiryDate = "Tue Sep 21 12:11:37 PHT 2021";
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(expiryDate, parserDtf);
System.out.println("Something will expire at " + zdt);
and it would output
Something will expire at 2021-09-21T12:11:37+08:00[Asia/Manila]
Changing the output format can be done via another DateTimeFormatter
, either use a built-in one as DateTimeFormatter.ISO_ZONED_DATE_TIME
or create a custom one by .ofPattern(pattern, Locale.ENGLISH)
or using a DateTimeFormatterBuilder
.
Considering your requirement to format and output the date part only, you have the option to simply extract the date part (that's a LocalDate
) and format that in java.time
:
String expiryDate = "Tue Sep 21 12:11:37 PHT 2021";
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(expiryDate, parserDtf);
LocalDate expiryLocalDate = zdt.toLocalDate();
System.out.println("Something will expire at "
+ expiryLocalDate.format(DateTimeFormatter.ofPattern("MMM dd uuuu",
Locale.ENGLISH)));
will output
Something will expire at Sep 21 2021
Read more about java.time
in the Trails.