I have a function that needs to check a datetime against a supplied datetime. My function is shown below (it works fine however I don't like it). The only thing that needs to change is the operator but currently I have a few if, else if's etc & lines of code that have been copied.
I'm sure I'm being stupid and there is a much better way of doing this?
enum DateTimeOperator
{
Equals = 0, GreaterThanOrEqualTo, GreaterThan, LessThan
}
My function
bool DateChecked(DateTime dateCheck DateTimeOperator dateOperator)
{
if(dateOperator == DateTimeOperator.Equals)
{
if (File.GetLastWriteTime(filePath + fileName).Date == dateCheck .Date)
return true;
else
return false;
}
else if(dateOperator == DateTimeOperator.GreaterThanOrEqualTo)
{
if (File.GetLastWriteTime(filePath + fileName).Date >= dateCheck .Date)
return true;
else
return false;
}
else if(dateOperator == DateTimeOperator.LessThan)
{
if (File.GetLastWriteTime(filePath + fileName).Date < dateCheck .Date)
return true;
else
return false;
}
}
Just for fun without if
/switch
:
Dictionary<DateTimeOperator, Func<DateTime, DateTime, bool>> operatorComparer = new Dictionary<DateTimeOperator, Func<DateTime, DateTime, bool>>
{
{ DateTimeOperator.Equals, (a, b) => a == b },
{ DateTimeOperator.GreaterThanOrEqualTo, (a, b) => a >= b },
{ DateTimeOperator.GreaterThan, (a, b) => a > b },
{ DateTimeOperator.LessThan, (a, b) => a < b }
};
bool DateChecked(DateTime dateCheck, DateTimeOperator dateOperator)
{
//TODO: add a sanity check
return operatorComparer[dateOperator](File.GetLastWriteTime(filePath + fileName).Date, dateCheck .Date);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With