c# datetime and sql datetime


  • hi,
    i use
    SELECT time from ***

    to get a datetime from my sql database.

    and in c#, my current time is:

    when i was using 
    timespan ts = cmd.ExecuteScalar() - DateTime.Now;

    it told me that cmd.ExecuteScalar() is an object while DateTime.Now is in format of datetime.

    but when i use to print out cmd.ExecuteScalar().getType().ToString(); and DateTime.Now.getType().ToString(); they both returns system.datetime.

    how can i get the timespan from the one i retrive from sql server and another from c#.
    Thursday, March 27, 2008 8:34 AM


All replies

  • Does this help?


    timespan ts = ((DateTime)cmd.ExecuteScalar()) - DateTime.Now;

    Thursday, March 27, 2008 8:36 AM
  • thanks, it works.

    but why cmd.ExecuteScalar().getType().ToString()
    and DateTime.Now

    returns the same result system.datetime?
    Thursday, March 27, 2008 8:40 AM
  • In your case, since you are querying for DateTime from Sql, the inherrent type returned is a DateTime. However the method ExecuteScalar is written to support returning of all possible types and hence uses the base of all types, i.e. System.Object.


    When you execute the method, the actual type returned is DateTime. Invoking GetType, thus internally is invoked on DateTime, since that is the contained type at that moment and hence returns System.DateTime. If you had queried for an int or a string, you would have got System.Int32 or System.String


    To be able to use the value returned by ExecuteScalar as right type, you will have to do a type casting


    Thursday, March 27, 2008 8:45 AM
  • thanks very much Atul Gupta!
    Thursday, March 27, 2008 8:52 AM