Use SQL Server time datatype in C#.NET application?

C#.NetSqlSql ServerTime

C# Problem Overview


How does one use the SQL time datatype introduced in SQL Server 2008 in C#.NET?

I've been trying to get it to work but no success.

C# Solutions


Solution 1 - C#

Here is an MSDN article that reviews all the new Date and Time datatypes introduced in SQL Server 2008 with respect to ADO.NET. As the document says: For System.Data.DbType.Time you would use the .NET Framework type System.TimeSpan

Solution 2 - C#

I think you can use TimeSpan datatype for your purpose. Here is an article that explains the use of Time datatype in ADO.NET.

Solution 3 - C#

Also even people from Microsoft tend to recommend mapping the sql datatype time to System.Timestamp I would not recommend doing so,

since the range of sql time is 00:00:00.0000000 - 23:59:59.9999999

wheras the range of System.TimeSpan is 10675199.02:48:05.4775808 - 10675199.02:48:05.4775807

which is just slightly different and can lead to nasty runtime out of range errors.

Solution 4 - C#

you can read it using datareader using something similar to following statement .

TimeSpan time = dr.GetTimeSpan(dr.GetOrdinal(“Time7FieldName”));

Solution 5 - C#

How are you accessing the data? Using Entity Frameworks, StoredProcedures etc.
If you have to pass a string representation of the date make sure that you do it in the format "yyyy-mm-dd hh:mm:ss" otherwise you will run the risk of the dd/mm/yyyy vs mm/dd/yyyy confusion. If you are using Entity Framework or DataSets then you should just pass the parameter a DataTime instance eg DateTime.Now

Solution 6 - C#

if your field is in time u can simply cast with (Timespan),

 while (reader.Read())
        {
             TimeSpan DBStartTime = (TimeSpan)reader["StartTime"];
             TimeSpan DBEndTime = (TimeSpan)reader["EndTime"];
            
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrdkView Question on Stackoverflow
Solution 1 - C#Simen SView Answer on Stackoverflow
Solution 2 - C#LavView Answer on Stackoverflow
Solution 3 - C#Michael SanderView Answer on Stackoverflow
Solution 4 - C#Imran RizviView Answer on Stackoverflow
Solution 5 - C#Jonathan StantonView Answer on Stackoverflow
Solution 6 - C#AweelmarchonsView Answer on Stackoverflow