如何将 LocalDate 对象格式化为 MM/dd/yyyy 并保持格式 [英] How to format LocalDate object to MM/dd/yyyy and have format persist

查看:116
本文介绍了如何将 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 并保持格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆