如何根据周数和年份获得周持续时间

时间:2015-05-27 11:05:12

标签: c# date datetime

我尝试过以下解决方案,但我无法实现。

例如:2015年7月15日应返回2015年2月15日→2015年2月21日

private string GetWeekPeriod(string weekYear)
{
    CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;
    int firstDayOfWek = (int)defaultCultureInfo.DateTimeFormat.FirstDayOfWeek;
    string result = string.Empty;
    string[] weekAndYear = weekYear.Split(new char[] { ',' });
    int week = Convert.ToInt32(weekAndYear[0]);
    int year = Convert.ToInt32(weekAndYear[1]);

    DateTime jan1 = new DateTime(year, 1, 1);
    int daysOffset = firstDayOfWek - (int)jan1.DayOfWeek;

    DateTime firstDayOfWeek = jan1.AddDays(daysOffset);
    var cal = CultureInfo.CurrentCulture.Calendar;
    var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
    int firstWeek = cal.GetWeekOfYear(firstDayOfWeek, dateTimeFormat.CalendarWeekRule, dateTimeFormat.FirstDayOfWeek);

    if (firstWeek <= 1)
    {
        week -= 1;
    }

    DateTime endDate = firstDayOfWeek.AddDays((week * 7) - 1);
    DateTime startDate = endDate.AddDays(-6);
    result = startDate.ToShortDateString() + " - " + endDate.ToShortDateString();

    return result;
}

1 个答案:

答案 0 :(得分:0)

在跟随@AlexBell提供的链接后。

我必须将startDate和endDate更改为以下内容并且有效

DateTime startDate = firstDayOfWeek.AddDays(week * 7);
     DateTime endDate = startDate.AddDays(6);