获取c#中给定月份和年份的最后日期

时间:2016-01-27 10:16:07

标签: c#

我希望使用c#代码获取指定月份和年份的最后一周日期。

假设给定的月份是1年,而年份是2016年那么方法应该归还给我

--01/02/2016
--01/09/2016
--01/16/2016
--01/23/2016
--01/30/2016
--02/06/2016

3 个答案:

答案 0 :(得分:0)

public static DateTime GetLastDateofWeek(int yr,int mnth,int week)         {             DateTime dt = new DateTime(yr,mnth,1);             DateTime newdate = new DateTime();             if(dt.DayOfWeek == DayOfWeek.Monday)             {                 newdate = dt.AddDays(((week - 1)* 7)+ 5);             }             其他             {                 newdate = dt.AddDays((8 - (int)dt.DayOfWeek)%7 +((week - 2)* 7)+ 5);             }             返回newdate;         }

答案 1 :(得分:0)

首先获得月份和年份,例如:

int year = 2016;
int month = 1;

然后创建一个代表第一个星期六的DateTime类的新实例。

DateTime firstsaturday = new DateTime(year,month,1);

while(firstsaturday.DayOfWeek != DayOfWeek.Saturday)
{
    firstsaturday = firstsaturday.AddDays(1);
]

然后创建一个DateTime值列表。

List<DateTime> saturdays = new List<DateTime>();

saturdays.Add(firstsaturday);

然后使用循环循环所有星期六。

DateTime CurrentSaturday = firstsaturday;

while(CurrentSaturday.AddDays(7).Month == month)
{
    CurrentSaturday = CurrentSaturday.AddDays(7);
    Saturdays.Add(CurrentSaturday);
}

答案 2 :(得分:0)

所以你想要一个需要一年零一个月作为参数并返回日期的方法。这些日期应该是该月所有星期的最后日期,也可能是以下几个月的日期。

这应该适用:

import

您的样本:

public static IEnumerable<DateTime> GetLastWeekDatesOfMonth(int year, int month, DayOfWeek firstDayOfWeek = DayOfWeek.Monday, bool includeLaterMonths = false)
{ 
    DateTime first = new DateTime(year, month, 1);
    int daysOffset = (int)firstDayOfWeek - (int)first.DayOfWeek;
    if (daysOffset < 0)
        daysOffset = 7 - Math.Abs(daysOffset);
    DateTime firstWeekDay = first.AddDays(daysOffset);
    DateTime current = firstWeekDay.AddDays(-1); // last before week start
    if (current.Month != month)
        current = current.AddDays(7);
    yield return current;
    if (includeLaterMonths)
    {
        while (true)
        {
            current = current.AddDays(7);
            yield return current;
        }
    }
    else
    { 
        while((current = current.AddDays(7)).Month == month)
            yield return current;
    }
}