如何创建一个包含该月第一周的日期的列表? (C#)

时间:2016-09-12 14:11:24

标签: c# datetime xamarin calendar xamarin.forms

是否可以这种格式进行?

public static int[,] Values

1 个答案:

答案 0 :(得分:1)

我感觉很慷慨,试试这个,但请注意,在你的问题中,你的阵列尺寸是倒退的恕我直言......

        // Inputs
        int year = 2016;
        int month = 9;
        int numberOfWeeksToList = 5;

        // Create a datetime object for the first day of the month you're interested in
        var firstOfMonth = new DateTime(year, month, 1);

        // Get the day of the week for that date
        var dowForFirstOfMonth = (int) firstOfMonth.DayOfWeek;

        // You want to start the week on a Monday, so get the difference between the days
        // -- note the DayOfWeek property has 0 for Sunday, so we add a week and mod to handle
        //    negative differences
        var numberOfDaysFromPreviousMonthToInclude = (dowForFirstOfMonth - (int) DayOfWeek.Monday + 7)%7;

        // The first date to include is the first date of the month subtract the number of days
        // from the previous month to include, i.e. stepping back in time a few days
        var firstDateToList = firstOfMonth.AddDays(-numberOfDaysFromPreviousMonthToInclude);

        // Create a 2D array, with the minor dimension representing one week
        int[,] daysInMonthByWeek = new int[numberOfWeeksToList, 7];

        // Now loop through each week's worth of dates, up to the configured number of weeks ...
        int dateIndex = 0;
        for (int weekIndex = 0; weekIndex < numberOfWeeksToList; ++weekIndex)
        {
            for (int dayIndex = 0; dayIndex < 7; ++dayIndex)
            {
                // Add the date index to the previously-computed first date to be displayed, and
                // include the 'Day' component of the date
                daysInMonthByWeek[weekIndex, dayIndex] = firstDateToList.AddDays(dateIndex).Day;
                ++dateIndex;
            }
        }