如何获取周中的日期,也可以使用 53 周的年份?时间:2019-03-17 标签:c#
我做了一个函数来计算一年中的几周,效果很好。问题是我需要一种方法来获取本周的星期一。这是瑞典日历。
下面的代码适用于有 52 周的年份,但有些年份(如 2009 年)有 53 周。然后我从一月得到了一个日期作为星期一(不可能是正确的)。所以请帮助我让它工作多年。
我可能可以做的是检查这一年是否有 53 周,然后做一些检查,但我希望它能够顺利进行,而不需要特殊检查。
这是我想出的:
public static DateTime GetDateFromWeek(int year, int week)
{
//First day of the year
DateTime d = new DateTime(year, 1, 1);
GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench);
d = calendar.AddWeeks(d, week);
d = d.AddDays(1 - (double)d.DayOfWeek);
return d;
}
I have made a function to cound the weeks in a year, and that works fine. The problem is that I need a method to get the mondaydate of the week. This is a swedish calendar.
The code below works well for years that have 52 weeks, but some years(like 2009) has 53 weeks. Then I got a date from januari as the mondaydate(cant be right). So please help me to get it to work for all years.
What I probably could do is check if the year has 53 weeks and then do some checks but I'd like it to go smooth without special checks.
Here's what I've come up with:
public static DateTime GetDateFromWeek(int year, int week)
{
//First day of the year
DateTime d = new DateTime(year, 1, 1);
GregorianCalendar calendar = new GregorianCalendar(GregorianCalendarTypes.MiddleEastFrench);
d = calendar.AddWeeks(d, week);
d = d.AddDays(1 - (double)d.DayOfWeek);
return d;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您的基本问题是假设
DateTime d = new DateTime(year, 1, 1);
位于一年的第一周,但它可能属于前一周的第 52/53 周年。您可以在此处找到解决方案。
I think your base problem is the assumption that
DateTime d = new DateTime(year, 1, 1);
is in the first week of the year, but it could belong to week 52/53 of the previous year.You will find a solution here.
这应该可以做到:
This should do it:
您可能想看看以下问题,我认为这就是您要问的问题:
获取本周第一个星期一的日期?
You might want to have a look at the following question, I think it is what you are asking:
Get date of first Monday of the week?