Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type to store time in C# and corresponding type in T-SQL

Tags:

c#

tsql

time

I would like to know how to store time in C# and T-SQL. I know that both of them provide a DateTime type but I just need to store a time. For instance:

var startTime = 9PM;
var endTime = 10PM;

And then store/retrieve this values from a database. Thanks in advance.

Francesco

like image 419
CiccioMiami Avatar asked Jun 08 '11 12:06

CiccioMiami


People also ask

What data type is time in C?

time_t is the simplest data type used to represent simple calendar time. In ISO C, time_t can be either an integer or a floating-point type, and the meaning of time_t values is not specified.

Is there a date type in C?

The C documentation about date indicates that you can use the time_t type which expresses a date with the number of seconds elapsed since a specific date called Epoch.


1 Answers

C#

Whether to use a DateTime or TimeSpan type in C# to store 9 PM is up to taste. Personally, I'd use DateTime, leaving the date component empty, since that's semantically closer to what you want. (A TimeSpan is designed to hold time intervals, such as "21 hours".)

The documentation supports both options. This is from the documentation of TimeSpan:

The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.

On the other hand, the MSDN article Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo mentions the following:

The DateTime structure is suitable for applications that do the following:
* Work with dates only.
* Work with times only.
[...]


T-SQL

SQL Server has a time data type.

like image 156
Heinzi Avatar answered Dec 08 '22 10:12

Heinzi