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

时间:2023-03-03
本文介绍了如何将 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 并保持格式不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:用科学计数法格式化双精度值 下一篇:打印出数组中的元素,除了最后一个单词之外的元素之间用逗号分隔

相关文章