How to convert Datareader DbType.Time Result to a Timespan?

I am reading the result from a MS SQL 2008 database with the dbtype.time column type from datareader using C # with a DAAB 4.0 map.

My problem is that the MSDN docs say that dbtype.time should map to a time interval, but the only closing constructor for the time period that I see is long, and the result returned from the datareader cannot be dropped to long or directly in time

I found this article that shows the datareader.getTimeSpan () method, but the datareader in daab 4.0 does not seem to have this method.

So, how do I convert the result from a datareader to a timepan object?

+6
c # time data-access timespan
source share
4 answers

GetTimeSpan is an OleDbDataReader and SqlDataReader method (but no more general IDataReader interface returned by DAAB ExecuteReader ). I assume that the IDataReader instance that DAAB returned to you is actually an SqlDataReader instance. This allows you to access the GetTimeSpan method by GetTimeSpan appropriate IDataReader instance:

 using (IDataReader dr = db.ExecuteReader(command)) { /* ... your code ... */ if (dr is SqlDataReader) { TimeSpan myTimeSpan = ((SqlDataReader)dr).GetTimeSpan(columnIndex) } else { throw new Exception("The DataReader is not a SqlDataReader") } /* ... your code ... */ } 

Edit: if the IDataReader instance is not SqlDataReader , you may miss the provider attribute of your connection string defined in your app.config (or web.config).

+6
source share

Have you tried the live broadcast?

 TimeSpan span = (TimeSpan)reader["timeField"]; 

I just quickly tested it on my machine and it works great when "timeField" is a data type of time in a database (SQL).

+9
source share

Here is my trick:

 using (IDataReader reader = db.ExecuteReader(command)) { var timeSpan = reader.GetDateTime(index).TimeOfDay; } 

Cleaner, maybe!

+1
source share

What is the type of value of a .NET column? If it's a DateTime, you can pass the value of your Ticks (long) property to the TimeSpan constructor. For example.

 var span = new TimeSpan(colValue.Ticks); 
0
source share

All Articles