为什么sdf.format(date)在Java中将2018-12-30转换为2019-12-30? [英] Why does sdf.format(date) converts 2018-12-30 to 2019-12-30 in java?
问题描述
我正在尝试将日期转换为字符串,但转换时将2018年更改为2019年。
我尝试了不同的日期,它可以工作。只会在2018年12月30日和12月31日失败。
SimpleDateFormat fmt = new SimpleDateFormat( YYYY-MM-dd);
Date date = fmt.parse( 2018-12-30);
字符串date2 = fmt.format(date);
预期结果:2018-12-30
实际结果:2019-12-30
区分大小写
大写字母 YYYY
表示基于周的年份,而不是日历年(小写的 yyyy
)。
所以您看到的是功能,而不是错误。根据 SimpleDateFormat
使用的一周的定义,到2018年的第二天是在2019年的第一周。该定义因 Locale
的不同而有所不同。 $ b
您使用的是可怕的日期时间类,而这些类在几年前被JSR 310中定义的现代 java.time 类所取代。
< h1>
LocalDate
LocalDate
类适用于您的字符串输入。
字符串输入= 2019-12-30;
LocalDate ld = LocalDate.parse(input);
I am trying to convert date to string but the year 2018 gets changed to 2019 while conversion.
I tried with different dates, it works. It only fails for December 30 and December 31 2018.
SimpleDateFormat fmt = new SimpleDateFormat("YYYY-MM-dd");
Date date = fmt.parse("2018-12-30");
String date2 = fmt.format(date);
Expected result: 2018-12-30
Actual result: 2019-12-30
Case-sensitive
Uppercase YYYY
means year of a week-based year rather than a calendar year (lowercase yyyy
).
So you are seeing a feature, not a bug. The second to the last day of 2018 is in the first week of 2019 according to the definition of a week used by SimpleDateFormat
. That definition varies by Locale
.
Avoid legacy date-time classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
LocalDate
The LocalDate
class is appropriate to your string inputs.
String input = "2019-12-30" ;
LocalDate ld = LocalDate.parse( input ) ;
这篇关于为什么sdf.format(date)在Java中将2018-12-30转换为2019-12-30?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!