鉴于计算在C#中的周数和年份一周的开始和结束日期(根据ISO规范) [英] Calculate the start and end date of a week given the week number and year in C# (based on the ISO specification)

查看:1262
本文介绍了鉴于计算在C#中的周数和年份一周的开始和结束日期(根据ISO规范)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个报告,显示52周年(或53周为几年有)和他们的开始和结束日期。有一个ISO规范要做到这一点,但似乎非常复杂! IM希望有人知道的方式做到这一点在C#或Visual Basic(它实际上是Visual Basic 6的,但我会尝试将它移植跨)

I need to generate a report that shows the 52 weeks of a year (or 53 weeks as some years have) and their start and end dates. There is an ISO spec to do this but seems awfully complicated! Im hoping someone knows of a way to do it in C# or Visual Basic (its actually for Visual Basic 6 but I will try port it across)

推荐答案

您可以使用 Calendar.GetWeekOfYear 方法来获取日期的周数,用 CalendarWeekRule.FirstFourDayWeek 值,以指定星期确定,而 DayOfWeek.Monday 来指定第一个周日。 。这是继ISO规范

You can use the Calendar.GetWeekOfYear method to get the week number of a date, with the CalendarWeekRule.FirstFourDayWeek value to specify how the weeks are determined, and DayOfWeek.Monday to specify the first weekday. That follows the ISO specification.

例如:

int week = Calendar.GetWeekOfYear(DateTime.Today, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

要获得今年的第一周的第一天,你可以从一月4日开始回去,直到找到星期一:

To get the first date of the first week of the year, you can start from the 4th of january and go back until you find the monday:

DateTime t = new DateTime(DateTime.Today,Year, 1, 4);
while (t.DayOfWeek != DayOfWeek.Monday) t = t.AddDays(-1);

这篇关于鉴于计算在C#中的周数和年份一周的开始和结束日期(根据ISO规范)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆