如何检查日期是在两天之间

时间:2016-06-28 06:00:34

标签: c# datetime date-comparison

我必须检查我的具体日期是在两个字符串天之间还是等于它们 例如:

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

2 个答案:

答案 0 :(得分:3)

您可以使用DayOfWeek枚举。

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))
   )
{

}

答案 1 :(得分:2)

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

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

这应适用于所有组合,因为如果它们在开始日之前预计会进入“下一周”。