C# DateTime check is incorrect
I've got a 开发者_运维百科little problem with some code of mine. The case is as follows:
There is a ListView which contains some measurement data. One of the data items is a status. This status can be 10, 20 of 30. This depends on the value of the next measurement date.
What I do is this. I take the next measurement date and check if the current data + 3 month is higher then the next measurement date. If so, I return status 30. If the current date >= the next measurement date, I should return 20. Else I return 10.
So, in short: current date + 3 months > next measurement date = status 30; current date >= next measurement date = status 20; else = status 10;
The problem is that when the next measement date is higher then the next measurement date, status 30 is allways returned. Below is my code:
private string getMsaStatus(DateTime dtNextMsa)
{
if (DateTime.Now.AddMonths(3) > dtNextMsa)
{
return "30";
}
else if (DateTime.Now >= dtNextMsa)
{
return "20";
}
else
{
return "10";
}
}
You need to change it like this:
if (DateTime.Now >= dtNextMsa.AddMonths(3))
{
return "30";
}
else if (DateTime.Now >= dtNextMsa)
{
return "20";
}
else
{
return "10";
}
This code takes into account the clarification in your comment.
精彩评论