2013-07-05 120 views
1

如何使用c#.net 2.0獲取例如'2013年4月第一個星期三'的日期?獲取特定年份的第一個星期日期

在.net中是否有這種工作的輔助方法,或者我應該寫自己的輔助方法?如果沒有這種工作的方法,請幫我寫出我自己的方法。

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

順利拿到這個月的第一天,增加1天,當你找到匹配'DayOfWeek' – V4Vendetta

回答

1

在@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; 
    } 
2

.NET Framework可以很容易地確定特定日期的星期幾,並顯示特定日期的本地化星期幾名稱。

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

+0

停頓,不知道這是否有助於在獲得「2013年4月的第一個星期三」 * * – V4Vendetta

+0

它擁有一切是如何信息和實現來編寫你自己的代碼來完成任務 –

4
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)); 
} 
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) 
相關問題