Oshrib
Oshrib

Reputation: 1880

Compare Datetime.now to date on SQL table

I'm trying to write code on c# that will compare between date that i have on SQL table (table:items, column "endTime") against datetime.now and by the result - display image.

example:

if the time on the column table is before the time now.. so display on the aspx image1, else display image2.

i've tried to do that by sql command:

    private DateTime endTime(out int lastDate)
{
    SqlConnection connection = new SqlConnection("Data Source=******;Initial Catalog=******;User ID=*****;Integrated Security=False;");
    string commandtext = "SELECT TOP(1) endTime FROM items";
    SqlCommand command = new SqlCommand(commandtext, connection);
    connection.Open();
    SqlCommand command2 = new SqlCommand(commandtext, connection);
    lastDate = (int)command2.ExecuteScalar(); 
    connection.Close();
    return ...
}

but i have problem with the return, and with the execution of the method... :

            int d; 
        Console.WriteLine(endTime(out d));
        if (d < DateTime.Now)
        {
            image1.Visible = true;

        }
        else
        {
            image2.Visible = true;
        }
        Console.WriteLine(d);

but i got error, but i believe it's come from the return.

Upvotes: 0

Views: 1384

Answers (4)

vivek
vivek

Reputation: 19

Instead of if (d < DateTime.Now) use this: if (d < DateTime.Now.Date)

Upvotes: 2

Randy
Randy

Reputation: 16677

i would suggest letting the database do the date comparison right in the sql.

SYSDATE can be compared to EndTime right in the query, and you can either not bring back rows that dont match (which allows you to process every row in the result set equally) or you check a simple value in the return set to see if the time is in the right period.

Upvotes: 0

sll
sll

Reputation: 62484

  1. What is returned by your sql query (I believe ticks)?
  2. How do you convert int into DateTime, show a code please
  3. Enclose SqlConnection in using() block as shown below:
using (SqlConnection connection = new SqlConnection(...))

Upvotes: 0

skaz
skaz

Reputation: 22580

Shouldn't you be casting out a DateTime from your query and not an int? Also, the stack trace/debugger should give you the line number of the exception. Can you post the stack trace?

Upvotes: 0

Related Questions