日历类(例如 GregorianCalendar)具有一个 TwoDigitYearMax
属性,该属性定义 100 年范围内的最后一年,该范围可以由两位数年份表示。 此属性通常用于将两位数的年份转换为四位数的年份。 以前, Calendar.TwoDigitYearMax 默认为 2029 年,适用于 GregorianCalendar 其他类似公历的日历,例如 JulianCalendar 和 EastAsianLunisolarCalendar。 该值意味着从 00 到 29 的两位数年份转换为 2000-2029 年。 从 30 到 99 的两位数年份转换为 1930-1999 年。 其他类似公历的默认 TwoDigitYearMax
属性值 GregorianCalendar 现已从 2029 年更改为 2049 年。 新值表示从 00 到 49 的两位数年份转换为 2000-2049。 从 50 到 99 的任何年份都将翻译为 1950-1999 年。
此外,在 Windows 上,属性的 TwoDigitYearMax
默认值现在从相应的 Windows 设置中获取(默认值现在也是 2049)。 这与 .NET 5 之前的行为匹配。
日期分析是受此更改影响最大的功能。
以前的行为
在 .NET 6 和 .NET 7 中,如果您未指定 TwoDigitYearMax 的值,使用公历分析“12/10/35”这样的字符串,会得到日期“1935 年 12 月 10 日”。
新行为
从 .NET 8 开始,使用公历分析类似“12/10/35”的字符串将生成日期“2035 年 12 月 10 日”。
已引入的版本
.NET 8 预览版 1
破坏性变更的类型
此更改为行为更改。
更改原因
更符合逻辑的做法是,分析一个两位数的年份,该年份相对接近两位数的当前年份,以生成一个本世纪(而不是上一个世纪)的四位数年份。 Windows作系统还将其默认设置更改为相同的数字(2049)。
建议的措施
如果不希望应用在将字符串分析为日期时依赖默认值,可以通过设置 TwoDigitYearMax 属性来控制两位数年份转换为四位数年份的方式。 以下代码显示如何为固定区域性设置该属性。
CultureInfo clonedInvariantCulture = (CultureInfo)(CultureInfo.InvariantCulture.Clone());
clonedInvariantCulture.DateTimeFormat.Calendar.TwoDigitYearMax = 2039; // Use any desired cutoff value.
DateTime dt = DateTime.Parse("12/25/45", clonedInvariantCulture);
受影响的 API
- System.DateOnly.Parse
- System.DateOnly.ParseExact
- System.DateOnly.TryParse
- System.DateOnly.TryParseExact
- System.DateTime.Parse
- System.DateTime.ParseExact
- System.DateTime.TryParse
- System.DateTime.TryParseExact
- System.DateTimeOffset.Parse
- System.DateTimeOffset.ParseExact
- System.DateTimeOffset.TryParse
- System.DateTimeOffset.TryParseExact
- System.Globalization.GregorianCalendar.TwoDigitYearMax (和其他像公历一样的日历类型)
- System.Globalization.GregorianCalendar.ToDateTime (和其他像公历一样的日历类型)
- System.Globalization.GregorianCalendar.ToFourDigitYear(Int32) (和其他像公历一样的日历类型)