Given a DateTime
, I want to check if the .Day
is between a number, say between 15 and 19.
So 9/16/2013
passes, but 9/20/2013
fails.
Thanks,
Given a DateTime
, I want to check if the .Day
is between a number, say between 15 and 19.
So 9/16/2013
passes, but 9/20/2013
fails.
Thanks,
Including
var date = DateTime.Now;
if (date.Day >= 15 && date.Day <= 19)
{
return true;
}
Excluding
var date = DateTime.Now;
if (date.Day > 15 && date.Day < 19)
{
return true;
}
I´m not 100% sure which one is right ;)
Something like this should work:
var date = DateTime.Now;
return (date.Day >= 15 && date.Day <= 19);
Since this is just a range, you can use less than or greater than operators for comparison. Also, you might use the >= or <= operators for including the start or end day.
An alternative approach based on the fact that only one predicate must be true for the date to be out of the range:
var date = DateTime.Now;
return !(date.Day < 15 || date.Day > 19)
if((DateTime.Today.Day >= 15) && (DateTime.Today.Day <= 19))
{
//do something
}
else
//do something else
}
Edit: (because of the error which you can see in the picture (in comments) i wasn't able to post the answer.)
private bool IsInRange(DateTime yourDate, DateTime lowestRange, DateTime highestRange) {
return yourDate.Day >= lowestRange.Day && yourDate.Day <= highestRange.Day;
}
You can use Day
property directly to check if your date is within some range using code from other answers.
MSDN says that
Starting with the .NET Framework 2.0, the DateTime structure contains a 64-bit field composed of a private Kind field concatenated with the Ticks field.
Therefore, the most efficient way to compare DateTime
instances is to use Ticks
property:
DateTime dateToValidate = SomeDate();
DateTime start = SomeRangeStart();
DateTime end = SomeRangeEnd();
return start.Ticks <= dateToValidate.Ticks && dateToValidate.Ticks <= end.Ticks;
To properly test if a date (day) is between given numbers, you must use the entire date, or the formula will fail if the date reaches the end of the month.
The example below checks the margin by adding days (or subtracticting days) by using AddDate
to greate the boundary date. Then check if the current date is between the boundaries.
var now = DateTime.Now;
if(date.AddDays(-5) < now && now < date.AddDays(5))
{
return true;
}