如何将 LocalDate 对象格式化为 MM/dd/yyyy 并保持格式不变

How to format LocalDate object to MM/dd/yyyy and have format persist(如何将 LocalDate 对象格式化为 MM/dd/yyyy 并保持格式不变)
本文介绍了如何将 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 并保持格式不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)