Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add days to DateTime returns value of 0?

This code counts number of records in an MSSQL table where a date is between today's date and today's date + 8 days, but it doesn't work; it returns a value of 0, but 2 is the right answer.

If I change DateTime.Now.AddDays to 7 or less it works as it should.

//Ordre klar til bestilling
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE udlevering BETWEEN @date and @dateadd";
command.Parameters.AddWithValue("@date", DateTime.Now.ToString("dd/MM/yyyy"));
command.Parameters.AddWithValue("@dateadd", DateTime.Now.AddDays(+8).ToString("dd/MM/yyyy"));

con.Open();
command.ExecuteNonQuery();
string result0 = command.ExecuteScalar().ToString();

con.Close();
MessageBox.Show(result0);

if (result0 != "0")
{
    bestillingToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}
like image 416
user3888775 Avatar asked Dec 18 '25 18:12

user3888775


1 Answers

Don't treat dates/times as strings. Just:

command.Parameters.AddWithValue("@date", DateTime.Now);
command.Parameters.AddWithValue("@dateadd", DateTime.Now.AddDays(8));

The problem could well be date/time formats.

Note that you are actually executing it twice for no reason; you can remove the command.ExecuteNonQuery().

Finally, don't treat integers as strings:

int count = (int)command.ExecuteScalar();
if(count != 0)  { .... }
like image 166
Marc Gravell Avatar answered Dec 20 '25 06:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!