System.Globalization.Calendar.GetWeekOfYear() 返回奇怪的结果
我正在计算日期的周数,但 System.Globalization.Calendar
返回 2007 年 12 月 31 日和 2012 年(以及其他年份)的奇怪结果。
Calendar calendar = CultureInfo.InvariantCulture.Calendar;
var date = new DateTime(2007, 12, 29);
for (int i = 0; i < 5; i++)
{
int w = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
Console.WriteLine("{0}\t{1}", date.ToString("dd.MM.yyyy"), w);
date = date.AddDays(1);
}
结果< /strong>
29.12.2007 52
30.12.2007 52
31.12.2007 53 <--
01.01.2008 1
02.01.2008 1
29.12.2012 52
30.12.2012 52
31.12.2012 53 <--
01.01.2013 1
02.01.2013 1
据我了解,2007 年和 2012 年不应该有第 53 周,但这些天应该包含在第 1 周中。有没有办法改变这种行为在日历
中?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
CalendarWeekRule 枚举的文档明确指出“不直接映射到 ISO 8601”,并链接到 Microsoft .Net 中的 ISO 8601 年份格式,描述差异的博客文章。
The documentation for the CalendarWeekRule enumeration specifically states that it "does not map directly to ISO 8601", and links to ISO 8601 Week of Year format in Microsoft .Net, a blog entry that describes the differences.
查看
CalendarWeekRule
的值。您正在使用 FirstFourDayWeek,因此您将获得您所描述的值。如果您希望每周恰好有 7 天,则应使用FirstFullWeek
。就您而言,这意味着 2007 年 12 月 31 日将是第 53 周,但 2008 年 2 月 1 日也是如此。
Have a look at the values of
CalendarWeekRule
. You are usingFirstFourDayWeek
, and so you are getting the values you describe. If you want every week to have exactly 7 days, you should useFirstFullWeek
.In your case, that would mean that 31. 12. 2007 will be week 53, but so will 2. 1. 2008.
从 .net core 3 开始,有一个新的 ISOWeek 实际上可以正确计算 WeekOfYear
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.isoweek.getweekofyear
Starting with .net core 3 there is a new ISOWeek that actually does calculate WeekOfYear correctly
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.isoweek.getweekofyear
周标识符不必是唯一的 52 周,只是特定周中不一定有 7 天。
如果这对您来说是个问题,那么添加代码来处理边缘情况。
There don't have to be 52 weeks for the week identifiers to be unique, you just don't necessarily have 7 days in a particular week.
If this is a problem for you then add code to handle the edge case.