我想比较一个日期,看看它是否在星期六之前是这样的:
//Check if Saturday YET
if (MYWorkDay.DayOfWeek < DateTime.DayOfWeek.Saturday)
IGottaWork();
else
Party();
似乎没有办法做到这一点。
有办法吗?
提前致谢
答案 0 :(得分:12)
为什么不呢?
if (MYWorkDay.DayOfWeek != DayOfWeek.Saturday
&& MYWorkDay.DayOfWeek != DayOfWeek.Sunday)
{
IGottaWork();
}
else
Party();
甚至更好:
List<DayOfWeek> partyDays = new List<DayOfWeek> {
DayOfWeek.Saturday, DayOfWeek.Sunday
};
if (partyDays.Contains(MYWorkDay.DayOfWeek))
Party();
else
IGottaWork();
答案 1 :(得分:3)
来自MSDN:
DayOfWeek枚举中的常量值的范围是 DayOfWeek.Sunday to DayOfWeek.Saturday。如果转换为整数,则为 值的范围从零(表示DayOfWeek.Sunday)到六 (表示DayOfWeek.Saturday)。
因此,您也可以使用大于和小于运算符进行计算。
//Check if Saturday YET
if (MYWorkDay.DayOfWeek < DayOfWeek.Saturday && MYWorkDay.DayOfWeek > DayOfWeek.Sunday)
IGottaWork();
else
Party();
答案 2 :(得分:1)
DayOfWeek是一个枚举,从星期日开始为0,星期六为最后一个元素,因此整数为6。比较时想一想。
答案 3 :(得分:1)
如果您希望进行比较而不是检查列表,您也可以这样做:
if ((MYWorkDay.DayOfWeek.CompareTo(DayOfWeek.Sunday) > 0) && (MYWorkDay.DayOfWeek.CompareTo(DayOfWeek.Saturday) < 0))
{
IGottaWork();
}
else
{
Party();
}
答案 4 :(得分:0)
试试这个:
if (new [] {DayOfWeek.Saturday, DayOfWeek.Sunday}.Contains(d.DayOfWeek)) {
// party :D
} else {
// work D:
}