问题
Hi guys i'm trying to compare two dates, for some reason the following code will return false, if i specify 25/05/2012 (startdate) and 31/05/12 (end date).
This only happens if 25th is used as the start date, works fine if i use 26th.
public bool IsValidDate(DateTime startDate, DateTime endDate)
{
return startDate < endDate && endDate > startDate;
}
what could be wrong?
回答1:
You must be mistaken something. For the given input you specified this code returns true
:
class Program
{
static void Main()
{
var startDate = new DateTime(2012, 5, 25);
var endDate = new DateTime(2012, 5, 31);
Console.WriteLine(IsValidDate(startDate, endDate));
}
public static bool IsValidDate(DateTime startDate, DateTime endDate)
{
return startDate < endDate && endDate > startDate;
}
}
Prints true
on the console.
Now of course repeating the exact same condition twice is meaningless. Stating the condition once is more than enough:
public bool IsValidDate(DateTime startDate, DateTime endDate)
{
return startDate < endDate;
}
回答2:
Why would you make a function to check if startDate < endDate
?
private void button1_Click(object sender, EventArgs e)
{
DateTime startDate = new DateTime(2012 , 05 , 25);
DateTime endDate = new DateTime(2012 , 05 , 31);
bool rtnval = IsValidDate(startDate, endDate);
}
public bool IsValidDate(DateTime startDate, DateTime endDate)
{
return startDate < endDate && endDate > startDate;
}
this code returns true!!!
break it up and check you have the values you want
public bool IsValidDate(DateTime startDate, DateTime endDate)
{
bool resulta = startDate < endDate; // break here
bool resultb = endDate > startDate; // break here
return startDate < endDate && endDate > startDate;
}
// oops i didn't realise its been answered already
来源:https://stackoverflow.com/questions/10750356/mvc-2-start-date-and-end-date-validation