首页 > 解决方案 > Reformat custom date from string

问题描述

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?

标签: javadate

解决方案


您需要区分解析日期(将 aString转换为DateorLocalDate类)和格式化日期(将DateorLocalDate类实例转换为 a String)。

要解析初始字符串,请使用:

LocalDate convertedDate = LocalDate.parse(date)

要格式化convertedDate,请使用:

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

编辑:我假设您至少在 Java 8 上,因此您可以使用较新的日期/时间类。有关更多信息,请参阅https://www.baeldung.com/java-8-date-time-intro 。


推荐阅读