月の週を使用して日付を決定する簡単な式?
質問
「2009 年 6 月の第 2 火曜日」や「2009 年 7 月の最後の金曜日」などの標準的なスケジュール情報が与えられた場合、それを日付に変換する最も簡単で効率的な式は何でしょうか?
入力:
w
=月の週、列挙(1日、2日、3日、4日、または最後)d
= 曜日、列挙型 日曜日から土曜日までm
= 月、整数y
= 年、整数
編集(もう一度) - 週が何曜日に始まるかは関係ありません。を手に入れたいです wの 3 番目のインスタンス d 指定された月に。したがって、厳密には 6 月の第 3 週に当たりますが、2009 年 6 月の第 2 日曜日は 6 月 14 日になります。同様に、6 月の第 1 日曜日は 6 月 7 日であり、null/例外ではありません。
解決
のような何かます:
static DateTime GetDate(int year, int month, DayOfWeek dayOfWeek,
int weekOfMonth) {
// TODO: some range checking (>0, for example)
DateTime day = new DateTime(year, month, 1);
while (day.DayOfWeek != dayOfWeek) day = day.AddDays(1);
if (weekOfMonth > 0) {
return day.AddDays(7 * (weekOfMonth - 1));
} else { // treat as last
DateTime last = day;
while ((day = day.AddDays(7)).Month == last.Month) {
last = day;
}
return last;
}
}
他のヒント
平日は月の最初の曜日と同じであったために尋ねられたときのバグを修正するために編集ます。
MARC BY問題ディスク「を修正するための第二編集
static DateTime GetDate(int year, int month,
DayOfWeek weekDay, int week)
{
DateTime first = new DateTime(year, month, 1);
int iDow = (int)weekday, iFirst = (int)first.DayOfWeek;
int adjust = (7+iDow-iFirst)%7 - 7;
return first.AddDays(7*week + adjust);
}
using System;
namespace date_using_week_of_month
{
public class Example
{
public static DateTime WthDayDOfMonthM( int w, DayOfWeek d, DateTime month )
{
return first( d, month ).AddDays( 7 * (w - 1) );
}
private static DateTime first( DayOfWeek d, DateTime month )
{
DateTime first = new DateTime(
month.Year, month.Month, 1 );
while ( first.DayOfWeek != d )
{
first = first.AddDays( 1 );
}
return first;
}
}
}
所属していません StackOverflow