java - 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?
解决方案
您需要区分解析日期(将 aString
转换为Date
orLocalDate
类)和格式化日期(将Date
orLocalDate
类实例转换为 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 。
推荐阅读
- python - 使用 python 操作 SVG 文件
- c# - WPF 数据网格绑定到数据表
- kubernetes - 如何为 Cockroachdb 创建 Kubernetes 客户端证书签名请求
- css - 基于数组在 SCSS 中动态创建 css 值列表
- css - Angular 6,如何根据变量(连续变化)改变img的风格(旋转、颜色、比例)
- lisp - CLISP 中的意外评估结果
- ruby-on-rails - Rails 对实例本身的条件关联
- django - Django - 通过“删除”方法从应用程序中删除记录和文件
- jquery - 在每个 li 文本后添加标签
- angular - 我应该为我的 Angular 6 应用程序使用 Angular Material 还是 Bootstrap Material?