我有月,年,星期和星期几,基于我想要约会。我怎样才能做到这一点?以下是我的代码,但我没有得到正确的结果。
我在这里缺少什么?
代码:
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
答案 0 :(得分:1)
今年的总统日是2月15日,所以这是正确的。 我有劳动节这样工作: 对于第一部分,我不得不假设你想将Microsofts DateTime(sunday = 0)翻译成你的Sunday = 1枚举。
public static DayOfWeek GetOneBasedDayOfWeek(DateTime date) // date = 9/1/2016 12:00:00 AM
{
// returns Thursday
return (DayOfWeek)((int)date.DayOfWeek + 1);
}
在你的主要功能中,你想要迭代,直到你实际达到一周中的某一天,而不仅仅是当它更少时(一旦你到达星期日,你的循环将永远停止,因为(int)Sunday < (int)AnyOtherDay
while (GetOneBasedDayOfWeek(firstDayOfWeek) != DayOfWeek)
我用几年后的日期对它进行了测试,似乎有效。