创建一年内的周列表

时间:2017-05-06 14:08:24

标签: c# datetime

问候我有以下模型:

   public class WeekOfYear
    {
        public int WeekNumber { get; set; }
        public DateTime FirstDayOfWeek { get; set; }
        public DateTime LastDayOfWeek { get; set; }
    }

目前我正在尝试根据一年中的几周创建一个列表,我必须知道我是哪一周,这一周的第一天和最后一天是什么,我已经研究了一下但是什么都没有出现,我知道如何获得WeekNumber,但是当我试图获得其他属性"本周的第一天/最后几天时,问题就开始了,任何人都有任何线索?它赞赏。

更新

让我说清楚,让我说我知道我在一年的第一周,我想知道的是一周的第一天是例如:2017-1-1星期一和最后一天是2017-1-7周日。

1 个答案:

答案 0 :(得分:2)

我前段时间做过类似的事情。我已将我的代码改编为您的课程,看看是否有帮助:

public static List<WeekOfYear> GetWeeksOfYear(int year)
{
    var weeksQuantity = GetNumberOfWeeksInYear(year);
    var weeksList = new List<WeekOfYear>();

    for (int i = 1; i <= weeksQuantity; i++)
    {
        var weekNumber = i;

        DateTime firstDay;
        DateTime lastDay;
        GetFirstAndLastDateOfWeek(year, weekNumber, out firstDay, out lasDay);

        weeksList.Add(new WeekOfYear
        {
            FirstDayOfWeek = firstDay,
            LastDayOfWeek  = lastDay,
            WeekNumber = weekNumber
        });
    }

    return weeksList;
}

public static int GetNumberOfWeeksInYear(int year)
{
    var dfi = DateTimeFormatInfo.CurrentInfo;
    var date1 = new DateTime(year, 12, 31);
    if (dfi != null)
    {
        Calendar cal = dfi.Calendar;
        return cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
            dfi.FirstDayOfWeek);
    }

    return 0;
}

public static void GetFirstAndLastDateOfWeek(int year, int weekOfYear, out DateTime firstDay, out DateTime lastDay)
{
    var ci = CultureInfo.CurrentCulture;

    DateTime jan1 = new DateTime(year, 1, 1);
    int daysOffset = (int)ci.DateTimeFormat.FirstDayOfWeek - (int)jan1.DayOfWeek;
    DateTime firstWeekDay = jan1.AddDays(daysOffset);
    int firstWeek = ci.Calendar.GetWeekOfYear(jan1, ci.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.FirstDayOfWeek);
    if ((firstWeek <= 1 || firstWeek >= 52) && daysOffset >= -3)
    {
        weekOfYear -= 1;
    }

    firstDay = firstWeekDay.AddDays(weekOfYear * 7);
    lastDay = firstDay.AddDays(6);
}