开发者

c# DateTime, Timespan question about period of times

开发者 https://www.devze.com 2023-02-16 19:44 出处:网络
What I\'m basically looking to do is monitor a period of time between 2 dates, say 01/01/2011 to 04/04/2011.

What I'm basically looking to do is monitor a period of time between 2 dates, say 01/01/2011 to 04/04/2011.

I am then looking for a way to then compare 2 new dates, where if these new dates fall between the above ones i can say assign a boolea开发者_开发问答n a value and if they dont i wont.

so if 02/02/2011 to 03/03/2011 then assign the boolean wheras if outside then no. ??


You can just use normal compare operators with DateTime to do this.

For example

public bool Check(DateTime d1, DateTime d2)
{
    DateTime StartDate = new DateTime(2011,1,1);
    DateTime EndDate = new DateTime(2011,4,4);

    return ((d1 >= StartDate && d1 <= EndDate) && (d2 >= StartDate && d2 <= EndDate));
}


This is a straight-forward as:

bool isInside = (testDate >= startDate && testDate <= endDate);


This example show how to check if a date is between two dates.

Code has been tested and works:

DateTime dtStart = new DateTime(2011, 02, 02);
DateTime dtEnd = new DateTime(2011, 03, 03);

if (DateTime.Now >= dtStart && DateTime.Now <= dtEnd)
{
    // Date is within range
}
0

精彩评论

暂无评论...
验证码 换一张
取 消