任何人都知道一个简单的方法来获取本周第一天的日期(欧洲的星期一).我知道年份和周数?我打算用C#做这个.
我对@HenkHolterman的解决方案有疑问,即使是@RobinAndersson的解决方案.
阅读ISO 8601标准很好地解决了这个问题.使用第一个星期四作为目标,而不是星期一.以下代码也适用于2009年第53周.
public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear) { DateTime jan1 = new DateTime(year, 1, 1); int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek; // Use first Thursday in January to get first week of the year as // it will never be in Week 52/53 DateTime firstThursday = jan1.AddDays(daysOffset); var cal = CultureInfo.CurrentCulture.Calendar; int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); var weekNum = weekOfYear; // As we're adding days to a date in Week 1, // we need to subtract 1 in order to get the right date for week #1 if (firstWeek == 1) { weekNum -= 1; } // Using the first Thursday as starting week ensures that we are starting in the right year // then we add number of weeks multiplied with days var result = firstThursday.AddDays(weekNum * 7); // Subtract 3 days from Thursday to get Monday, which is the first weekday in ISO8601 return result.AddDays(-3); }
我喜欢Henk Holterman提供的解决方案.但是为了更加独立于文化,你必须得到当前文化的一周的第一天(它并不总是星期一):
using System.Globalization; static DateTime FirstDateOfWeek(int year, int weekOfYear) { DateTime jan1 = new DateTime(year, 1, 1); int daysOffset = (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - (int)jan1.DayOfWeek; DateTime firstMonday = jan1.AddDays(daysOffset); int firstWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(jan1, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek); if (firstWeek <= 1) { weekOfYear -= 1; } return firstMonday.AddDays(weekOfYear * 7); }
最简单的方法可能是查找一年中的第一个星期一,然后添加相关的周数.这是一些示例代码.假设从1开始的周数,顺便说一下:
using System; class Test { static void Main() { // Show the third Tuesday in 2009. Should be January 20th Console.WriteLine(YearWeekDayToDateTime(2009, DayOfWeek.Tuesday, 3)); } static DateTime YearWeekDayToDateTime(int year, DayOfWeek day, int week) { DateTime startOfYear = new DateTime (year, 1, 1); // The +7 and %7 stuff is to avoid negative numbers etc. int daysToFirstCorrectDay = (((int)day - (int)startOfYear.DayOfWeek) + 7) % 7; return startOfYear.AddDays(7 * (week-1) + daysToFirstCorrectDay); } }
更新:.NET Core 3.0和.NET Standard 2.1附带了此类型。
好消息!一个拉请求加入System.Globalization.ISOWeek
到.NET的核心刚刚合并,目前内定为3.0版本。希望它将在不远的将来传播到其他.NET平台。
您应该能够使用该ISOWeek.ToDateTime(int year, int week, DayOfWeek dayOfWeek)
方法进行计算。
您可以在此处找到源代码。