princessbubbles15
princessbubbles15

Reputation: 65

Timespan in an if else statement

I have the following code, and I am planning to use it to check if the user has placed a correct number of days between two datetimepickers. I've searched on google, and some posts say use var, some say parse, and still it wont work, the message box won't pop up upon checking.

I have already made it work by using a label as a container of the result and use an if else statement to check if the text is equal to 14,15 or 16. It works cause i only need to detect if its 14, 15 or 16, but what if i was given a situation where i need to compare large numbers, I wish I a better solution than what i have right now.

Can someone please tell me how to compare time spans in an if else statement properly? Thank you so much. have a nice day :)

DateTime dateFrom = from_dtPicker.Value;
DateTime dateTo = to_dtPicker.Value;
TimeSpan DayDifference = dateTo - dateFrom;
double NumberOfDays = DayDifference.TotalDays;

if ((NumberOfDays < 14) && (NumberOfDays > 16)) 
{
    //message box
}

Here's what i mean with my weird solution though,

DateTime dateFrom = pp_from_dtPicker.Value;
DateTime dateTo = pp_to_dtPicker.Value;
TimeSpan DayDifference = dateTo - dateFrom;
numofdaysLBL.Text = DayDifference.TotalDays.ToString();

if ((numofdaysLBL.Text != "14") && (numofdaysLBL.Text != "15") && (numofdaysLBL.Text != "16"))
{
        //msgbox
}

Upvotes: 1

Views: 1969

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

You can write a function which will give you that NumberOfDays is in between given range or not

public bool IsGivenDateInRange(double numberOfDays, double startDate, double endDate)
{
  return numberOfDays >= startDate && numberOfDays <= endDate;
}

Now use this function in if condition

if(IsGivenDateInRange(NumberOfDays, 14, 16)) //Instead of 14 and 16 you can use any number
{
      //Your logic
}

As per new edit in your question if you want to show message box when date does not come in these range, then you can use same function but with negation

if(!IsGivenDateInRange(NumberOfDays, 14, 16)) //Instead of 14 and 16 you can use any number
{
      //MessageBox.Show();
      //Your logic
}

Upvotes: 1

user1781290
user1781290

Reputation: 2864

It seems to me, that your comparison is the problem here

if ((NumberOfDays < 14) && (NumberOfDays > 16))

NumberOfDays can never be less than 14 AND more than 16 at the same time. Instead invert the comparison:

if ((NumberOfDays >= 14) && (NumberOfDays <= 16))

EDIT: Maybe I misunderstood what you are asking (as pointed out in the comments). If you want a more generic solution for comparing dates, you can simply wrap your code into a function

bool AreDatesClose(DateTime d1, DateTime d2, double minDaysApart, double maxDaysApart)
{
    var timespan = d1 - d2;
    return timespan.TotalDays >= minDaysApart && timespan.TotalDays <= maxDaysApart;
}

Upvotes: 2

Related Questions