如何检查日期日期是在两个给定的日子之间

本文关键字:日期 两个 之间 日子 何检查 检查 | 更新日期: 2023-09-27 17:53:00

我必须检查我的特定日期日期是否在两个字符串日期之间或等于它们例如:

var startDay = "Saturday";
var endDay = "Tuesday";
DateTime myDate = DateTime.Now;
if(myDate.DayofWeek >= startDay && myDate.DayofWeek <= endDay){
//some code here...
}

如何检查日期日期是在两个给定的日子之间

您可以使用DayOfWeek enum

if(myDate.DayOfWeek >= DayOfWeek.Tuesday 
   && myDate.DayOfWeek <= DayOfWeek.Saturday)
{
    // This would catch the days from Tuesday to Saturday
}

如果你想赶上从星期六到星期二的日子,你必须稍微修改一下你的代码。

    if(myDate.DayOfWeek >= DayOfWeek.Saturday 
    || myDate.DayOfWeek <= DayOfWeek.Tuesday)
{
    // This would catch the days from Tuesday to Saturday
}

如果您的startDateendDate正在改变。然后您需要解析第一个,并做一些额外的检查。

DayOfWeek startDayOfWeek;
DayOfWeek endDayOfWeek;
if (!Enum.TryParse(startDay, out startDayOfWeek))
{
    // Something wrong happened and you have to handle it.
}
if (!Enum.TryParse(endDay, out endDayOfWeek))
{
    // Something wrong happened and you have to handle it.
}
if (
       ((int)startDayOfWeek < (int)endDayOfWeek
         && myDate.DayOfWeek >= startDayOfWeek
         && myDate.DayOfWeek <= endDayOfWeek)
    || ((int)startDayOfWeek > (int)endDayOfWeek
         && (myDate.DayOfWeek >= startDayOfWeek
             || myDate.DayOfWeek <= endDayOfWeek))
   )
{
}

您可以将这些字符串解析为DayOfWeek enum:

var startDay = "Saturday";
var endDay = "Tuesday";
DayOfWeek startDayOfWeek, endDayOfWeek;
if (!Enum.TryParse(startDay, out startDayOfWeek))
   // error handlnig
if (!Enum.TryParse(endDay, out endDayOfWeek))
   // error handlnig
DateTime myDate = DateTime.Now;
if(myDate.DayofWeek >= startDayOfWeek && myDate.DayofWeek <= endDayOfWeek){
    //some code here...
}

但这又带来了另一个问题:DayOfWeek的值从星期日(0)到星期六(6)。根据您定义的一周的开始或之间的含义,您可能需要调整值。

所以这是一个建议:

int startDayAsInt = (int)startDayOfWeek; // the parsed value from above
int endDayAsInt = (int)endDayOfWeek;
int myDateAsInt = (int)myDate.DayOfWeek;
if (endDayAsInt < startDayAsInt) endDayAsInt += 7;
if (myDateAsInt < startDayAsInt) myDateAsInt += 7;
if (myDateAsInt >= startDayAsInt && myDateAsInt <= endDayAsInt)
    // do something

这应该适用于所有组合,因为它会将日期投影到"下"周,如果它们是在开始日期之前。