0

如何使用 c# .net 2.0 获取例如“2013 年 4 月第一个星期三”的日期?

.net 中是否有此类工作的辅助方法,或者我应该编写自己的辅助方法?如果这种工作没有方法,请帮助我编写自己的方法。

DateTime GetFirstXDayFromY(string dayName, DateTime targetYearMonth)
{
    ///???
}
4

4 回答 4

3
public static DateTime GetFirstDay(int year, int month, DayOfWeek day)
{
    DateTime result = new DateTime(year, month, 1);
    while (result.DayOfWeek != day)
    {
        result = result.AddDays(1);
    }

    return result;
}

如果您使用的是 .net >= 3.5,则可以使用 Linq:

public static DateTime GetFirstDay(int year, int month, DayOfWeek dayOfWeek)
{
    return Enumerable.Range(1, 7).
                      Select(day => new DateTime(year, month, day)).
                      First(dateTime => (dateTime.DayOfWeek == dayOfWeek));
}
于 2013-07-05T09:08:43.100 回答
1

.NET Framework 可以轻松确定特定日期的星期几,并显示特定日期的本地化工作日名称。

http://msdn.microsoft.com/en-us/library/bb762911.aspx

于 2013-07-05T09:08:32.093 回答
1

请尝试使用以下代码片段。

    // Get the Nth day of the month
    private static DateTime NthOf(DateTime CurDate, int Occurrence, DayOfWeek Day)
    {
        var fday = new DateTime(CurDate.Year, CurDate.Month, 1);

        if (Occurrence == 1)
        {
            for (int i = 0; i < 7; i++)
            {
                if (fday.DayOfWeek == Day)
                {
                    return fday;
                }
                else
                {
                    fday = fday.AddDays(1);
                }
            }

            return fday;
        }
        else
        {

            var fOc = fday.DayOfWeek == Day ? fday : fday.AddDays(Day - fday.DayOfWeek);

            if (fOc.Month < CurDate.Month) Occurrence = Occurrence + 1;
            return fOc.AddDays(7 * (Occurrence - 1));
        }
    }

如何调用/使用它们?

NthOf(targetYearMonth, 1, DayOfWeek.Wednesday)
于 2013-07-05T09:13:18.127 回答
0

在@vc 和@Jayesh 的答案的帮助下,我想出了这个方法。非常感谢。

public static DateTime GetFirstDay(int year, int month, DayOfWeek day, int occurance)
{
    DateTime result = new DateTime(year, month, 1);
    int i = 0;

    while (result.DayOfWeek != day || occurance != i)
    {
        result = result.AddDays(1);
        if((result.DayOfWeek == day))
            i++;
    }

    return result;
}
于 2013-07-05T12:00:12.513 回答