How to format LocalDate object to MM/dd/yyyy and have format persist(如何将 LocalDate 对象格式化为 MM/dd/yyyy 并保持格式不变)
问题描述
我正在阅读文本并将日期存储为 LocalDate 变量.
I am reading text and storing the dates as LocalDate variables.
我有什么办法可以保留 DateTimeFormatter 的格式,这样当我调用 LocalDate 变量时它仍然是这种格式.
Is there any way for me to preserve the formatting from DateTimeFormatter so that when I call the LocalDate variable it will still be in this format.
我希望 parsedDate 以 25/09/2016 的正确格式存储,而不是作为字符串打印
I want the parsedDate to be stored in the correct format of 25/09/2016 rather than printing as a string
我的代码:
public static void main(String[] args)
{
LocalDate date = LocalDate.now();
DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu");
String text = date.format(formatters);
LocalDate parsedDate = LocalDate.parse(text, formatters);
System.out.println("date: " + date); // date: 2016-09-25
System.out.println("Text format " + text); // Text format 25/09/2016
System.out.println("parsedDate: " + parsedDate); // parsedDate: 2016-09-25
// I want the LocalDate parsedDate to be stored as 25/09/2016
}
推荐答案
考虑到您的编辑,只需将 parsedDate 设置为等于您的格式化文本字符串,如下所示:
Considering your edit, just set parsedDate equal to your formatted text string, like so:
parsedDate = text;
<小时>
LocalDate 对象只能以 ISO8601 格式 (yyyy-MM-dd) 打印.为了以其他格式打印对象,您需要对其进行格式化并将 LocalDate 保存为字符串,就像您在自己的示例中演示的那样
A LocalDate object can only ever be printed in ISO8601 format (yyyy-MM-dd). In order to print the object in some other format, you need to format it and save the LocalDate as a string like you've demonstrated in your own example
DateTimeFormatter formatters = DateTimeFormatter.ofPattern("d/MM/uuuu");
String text = date.format(formatters);
这篇关于如何将 LocalDate 对象格式化为 MM/dd/yyyy 并保持格式不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 LocalDate 对象格式化为 MM/dd/yyyy 并保持格式


基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01