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 并保持格式
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
