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
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.
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.
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.
[...]
SQL Server has a time
data type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With