上述方法计算出 2016 年第一周的第一个日期错误。
基于先前答案的固定代码
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));
}