如何将LocalDate对象格式化为MM / dd / yyyy,并且格式保持不变 [英] How to format LocalDate object to MM/dd/yyyy and have format persist
问题描述
有没有什么办法可以保留DateTimeFormatter的格式,所以当我调用LocalDate变量时,它仍然是这种格式。
编辑:我希望parsedDate被存储在25/09/2016的正确格式,而不是打印为字符串
我的代码:
public static void main(String [] args)
< /编辑:考虑到你的编辑,只需设置parsedDate等于你的格式化文本字符串,如下所示:
{
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); //文本格式25/09/2016
System.out.println(parsedDate:+ parsedDate); // parsedDate:2016-09-25
//我想将LocalDate parsedDate存储为25/09/2016
}
parsedDate = text;
LocalDate对象只能打印在ISO8601格式(yyyy-MM-dd)。为了以其他格式打印对象,需要格式化它,并将LocalDate保存为字符串,就像你在自己的例子中演示的那样。
DateTimeFormatter formatters = DateTimeFormatter.ofPattern(d / MM / uuuu);
String text = date.format(formatters);
I am reading text and storing the dates as LocalDate variables.
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.
EDIT:I want the parsedDate to be stored in the correct format of 25/09/2016 rather than printing as a string
My code:
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 }
解决方案EDIT: Considering your edit, just set parsedDate equal to your formatted text string, like so:
parsedDate = text;
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屋!