Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateOnly and TimeOnly mapping to SQL Server

When working with dates, I have been using DateTime2 type in SQL Server to store C# DateTime.

.NET 6 has introduced new structs such as DateOnly and TimeOnly. I assume these should be mapped to Date and Time.

Are there any corner cases when the conversion wouldn't be valid? Are these types fully compatible?

like image 984
Korfu Avatar asked Aug 02 '26 08:08

Korfu


2 Answers

For the ones that are nowadays in .NET 8 and above. Apparently now (if it wasn't in the past versions) is supported the native conversion, so you don't have to worry :)

enter image description here

enter image description here

like image 187
Jose Manuel Lepe Avatar answered Aug 05 '26 11:08

Jose Manuel Lepe


When saving time in SQL Server, for instance time(7), with retrieving the column data via a SqlDataReader, the value is returned as a TimeSpan.

This is not an equal conversion. To convert to a TimeOnly instance however, you can parse the stringyfied TimeSpan.

TimeOnly.Parse({timespanvalue}.ToString());

Not extremely elegant, but something to consider when dealing with TimeOnly and sql server time.

like image 38
Jorrit Reedijk Avatar answered Aug 05 '26 11:08

Jorrit Reedijk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!