tags:

views:

39

answers:

3

I tried the following

DateTime start = Convert.ToDateTime(TextBox1.Text);
DateTime end = Convert.ToDateTime(TextBox2.Text);
if (DateTime.Now.Date == start.Date || DateTime.Now.Date == end.Date || (DateTime.Now >= start.Date && DateTime.Now <= end.Date))
{
   lblResult.Text = "true";
}
else
{
   lblResult.Text = "false";
}

This verifies if the date range is one day also. Any way to reduce the number of conditions above?

+3  A: 
DateTime start = Convert.ToDateTime(TextBox1.Text);
DateTime end = Convert.ToDateTime(TextBox2.Text);
DateTime now = DateTime.Now;
if (now >= start.Date && now <= end.Date)
{
   lblResult.Text = "true";
}
else
{
   lblResult.Text = "false";
}
John Saunders
Younes
+1  A: 
DateTime dateStart = Convert.ToDateTime(TextBox1.Text); 
DateTime dateEnd = Convert.ToDateTime(TextBox2.Text); 

if (DateTime.Now.Date == dateStart .Date || DateTime.Now.Date == dateEnd .Date || (DateTime.Now >= dateStart .Date && DateTime.Now <= dateEnd .Date)) 
{ 
   lblResult.Text = "true"; 
} 
else 
{ 
   lblResult.Text = "false"; 
} 

In my opinion you can leave out those 2 checks:

DateTime.Now.Date == dateStart .Date || DateTime.Now.Date == dateEnd .Date

since

DateTime.Now >= dateStart .Date && DateTime.Now <= dateEnd .Date

is also checking wheter your startdate falls on today's date.

<= means smaller or the same.

Younes
+1  A: 

Only the last codition is needed, and you can take the Date part of the DateTime on converting. Use the Date part of Now, otherwise if the "start" and "end" strings are the same - the condition returns false (because when taking only the Date part of a DateTime, the time is represented as 00:00:00...)

DateTime start = Convert.ToDateTime(TextBox1.Text).Date;
DateTime now = DateTime.Now.Date;
DateTime end = Convert.ToDateTime(TextBox2.Text).Date;
if (now >= start && now <= end)
{
   lblResult.Text = "true";
}
else
{
   lblResult.Text = "false";
}

If you want to verify that the range contains only one day, just remove the "smaller than"/"greater than" conditionings:

(now = start && now = end)

thus making sure that "now" is the same date as "start" and "end", but this isn't really a "falls within range" check.

M.A. Hanin