Monday, July 11, 2022

DateOnly and TimeOnly structures are introduced in NET 6. Can you save them to the database?

 


     DateOnly and TimeOnly are the new members of .NET family, they are introduced in version 6. Developers have been asking to declare only a date or only a time without using the DateTime object for a long time. These two new functions will make the developer's life easy for sure. You can declare them easily but saving them to a database can be a challenge. Before we go into those details for saving them, Let's look at how to declare and use them in the code.

DateOnly(year, month, day)
TimeOnly(hour, min, sec, ms)

     As you can see in the following example, it gives us DayNumber, DayOfWeek, and DayOfYear properties with the date properties. 


     Here are the TimeOnly properties.


     Everything looks great so far. Usually, when you declare an object like this, you might need to save it to the database. Unfortunately, there is no easy way to save DateOnly and TimeOnly objects to SQL Server since there is no data type mapped to these objects. There are date and time data types in SQL Server but System.Data.SqlClient or Microsoft.Data.SqlClient does not support DateOnly or TimeOnly. We know System.Data.SqlClient will not receive any new features, you need to wait until  Microsoft add support for DateOnly and TimeOnly to Microsoft.Data.SqlClient. Until then, you need to convert DateOnly or TimeOnly to DateTime before you save it to SQL Server.

    You are lucky if you have a NoSQL database. Since you don't need to worry about schemas in NoSQL. You can easily save DateOnly or TimeOnly to NoSQL databases.

    I tried to declare a test class with DateOnly and TimeOnly properties and save it to Azure Cosmos DB. The result was surprisingly good. Cosmos DB SDK serialized the object as it is. I was expecting to see the result in a string. I was wondering how this would work with indexing.

Here is my Console code that creates an item in Azure Cosmos DB.


     This is what data looks like in Azure Cosmos DB. The object is serialized as an object rather than a string. Saving date or time in this format gives me a lot of flexibility when it comes to querying the data.



No comments:

Post a Comment