简体   繁体   中英

If statement - comparing datareader value to datetime

I'm hoping you guys can help with a little issue I'm having. I'm getting some errors when trying to check whether a datareader value is less than a specified dateTime value and need some help.

DateTime feedate = new DateTime(2013,09,01);
if (rsData["M_Start"] != DBNull.Value) & (Convert.ToDateTime(rsData["M_Start"]).ToString("yyyy/mm/dd") < feedate)

So the above is what I have and the errors I'm getting is the 'only assignment call increment decrement and new object expressions can be used as a statement' message.

I'm a bit stumped as C# is still really new to me so any help is appreciated!

Thanks.

  1. You should use the logical and && instead
  2. You should use DataReader.IsDBNull instead
  3. You should not compare a DateTime with a String , why do you convert it to string at all?

DateTime feedate = new DateTime(2013, 09, 01);
if (!rsData.IsDBNull(rsData.GetOrdinal("M_Start")) && (DateTime)rsData["M_Start"] < feedate)
{
    // ...
}

You have wrong parenthesis and 'and' operator. The code should read:

DateTime feedate = new DateTime(2013,09,01);
if (rsData["M_Start"] != DBNull.Value && Convert.ToDateTime(rsData["M_Start"]).ToString("yyyy/mm/dd") < feedate)
{
    // code
}

The & operator is a bit-wise or, while the && operator is a logical or. The if statement takes a condition in parenthesis like this: if (… condition goes here …) .

Note: As Tim Schmelter noted in his answer, there are several other flaws, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM