英文:
Convert Date to String shows error Field DayOfYear cannot be printed as the value 234 exceeds the maximum print width of 2
问题
我想将日期以不同的格式转换为字符串,但是我遇到了以下错误,
DateTimeException-Field DayOfYear无法打印,因为值234超过了最大打印宽度2
以下是不同的格式,
"MMDDYY"
"DD_MM_YY"
"YYYYMMDD"
"MMDD"
"DD-MM-YY"
以下是我的代码,
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("DD-MM-YY");
String formattToString = localDate.format(formatter);
我是否漏掉了什么?
英文:
I want to convert Date to String in different formats, but i am getting the below error,
DateTimeException-Field DayOfYear cannot be printed as the value 234 exceeds the maximum print width of 2
Below are the different formats,
"MMDDYY"
"DD_MM_YY"
"YYYYMMDD"
"MMDD"
"DD-MM-YY"
Below is my code,
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("DD-MM-YY");
String formattToString = localDate.format(formatter);
Am i missing something here ?
答案1
得分: 6
DD(大写)表示年的第DD天(即年中的天数),在这种情况下打印的是234,所以你需要将它替换为小写的dd,这样就可以正常工作了。在你的情况下,YY并没有引起错误,但是将它改为yyyy。尝试将你的代码修改如下:
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattToString = localDate.format(formatter);
这个教程中有一些模式示例:
http://tutorials.jenkov.com/java-internationalization/simpledateformat.html
英文:
DD (uppercase) means DD - day-of-year, in this case is printing 234, so you have to replace to dd (lowercase), that will work fine. YY is not causing the error in your case, but change It to yyyy. Try to change your code like it:
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattToString = localDate.format(formatter);
This tutorial has some Pattern Examples:
http://tutorials.jenkov.com/java-internationalization/simpledateformat.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论