我有月,年,星期幾和星期幾,基於我想得到一個日期。我怎樣才能做到這一點?以下是我的代碼,但我沒有得到正確的結果。如何從年,月,星期幾和星期幾獲取日期? C#
我在這裏錯過了什麼?
代碼:
internal DateTime? GetDate(int year) // year = 2016
{
int month;
DateTime? date;
switch (Type)
{
case "CALCULATED":
month = FixedMonth; // month = 9
var firstDayOfWeek = new DateTime(year, month, 1); // firstDayOfWeek = 9/1/2016 12:00:00 AM
while (RestaurantSchedule.GetOneBasedDayOfWeek(firstDayOfWeek) <= DayOfWeek) // DayOfWeek = Monday
{
firstDayOfWeek = firstDayOfWeek.AddDays(1);
}
date = firstDayOfWeek.AddDays((WeekOfMonth - 1) * 7); // WeekOfMonth = 1, returns date = 9/1/2016 12:00:00 AM
if (date.Value.Month > month)
{
return date.Value.AddDays(-7);
}
return date;
default:
return new DateTime?();
}
}
public static OneBasedDayOfWeek GetOneBasedDayOfWeek(DateTime date) // date = 9/1/2016 12:00:00 AM
{
// returns Thursday
return (OneBasedDayOfWeek)Enum.Parse(typeof(OneBasedDayOfWeek), date.DayOfWeek.ToString());
}
// OneBasedDayOfWeek uses following enum
public enum DayOfWeek
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 3,
Wednesday = 4,
Thursday = 5,
Friday = 6,
Saturday = 7
}
數據庫條目:
HolidayDefinitionId Type FixedMonth FixedDay DayOfWeek WeekOfMonth Adjustment HolidayName Enabled
-------------------- ------------ ----------- ----------- ----------- ----------- ----------- --------------- -------
LABOR CALCULATED 9 0 2 1 0 Labor Day 1
PRESIDENTS CALCULATED 2 0 2 3 0 President's Day 1
實際結果:
Presidents Day = 02/15/2016
Labor Day = 09/01/2016
預期結果:
Presidents Day = 02/16/2016
Labor Day = 09/05/2016
是'WeekOfMonth'不夠好界定?勞動節「的第一個星期一」在九月。如果9月一個星期二開始,那麼勞動節是在那個月的第二個星期,不是嗎?但是如果一年九月從星期日開始,那將是本月的第一週。 – Quantic
什麼是OneBasedDayOfWeek? – Kolichikov
@Kolichikov'使用OneBasedDayOfWeek = KI.TAS.DomainObjects.Day.DayOfWeek;'基本上使用所聲明的枚舉值。 – CSharper