上記のメソッドは、2016 年の第 1 週の最初の日付を間違って計算します。
以前の回答に基づいて修正されたコード
public DateTime FirstDateOfWeek(
int year,
int weekOfYear)
{
var newYear = new DateTime(year, 1, 1);
var weekNumber = newYear.GetIso8601WeekOfYear();
DateTime firstWeekDate;
if (weekNumber != 1)
{
var dayNumber = (int) newYear.DayOfWeek;
firstWeekDate = newYear.AddDays(7 - dayNumber + 1);
}
else
{
var dayNumber = (int)newYear.DayOfWeek;
firstWeekDate = newYear.AddDays(-dayNumber + 1);
}
if (weekOfYear == 1)
{
return firstWeekDate;
}
return firstWeekDate.AddDays(7 * (weekOfYear - 1));
}
プラステスト
[TestCase(2016, 1, 2016, 1, 4)]
[TestCase(2016, 2, 2016, 1, 11)]
[TestCase(2016, 52, 2016, 12, 26)]
[TestCase(2014, 1, 2013, 12, 30)]
public void FirstDateOfWeek_ShouldReturnCorrectDay(int year, int weekNumber, int correctYear, int correctMonth, int correctDay)
{
var helper = new DateHelper();
var result = helper.FirstDateOfWeek(year, weekNumber);
Assert.That(result.Year, Is.EqualTo(correctYear));
Assert.That(result.Month, Is.EqualTo(correctMonth));
Assert.That(result.Day, Is.EqualTo(correctDay));
}