Convert Date to String shows error Field DayOfYear cannot be printed as the value 234 exceeds the maximum print width of 2

huangapple go评论108阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月22日 23:23:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63537849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定