Could life be made easier by saving DateTime values as a long
instead? There always seem to be problems when working with null DateTime values, whether storing
No, use a datetime
column.
There always seem to be problems when working with null DateTime values
If your column is nullable, and you for some reason have difficulties when the type of the column is datetime
you will also have problems when the type of the column is long
.
... invalid DateTimes
How do you get invalid datetimes into a datetime
column? One of purposes of using the datetime
column to begin with is that sort of validation happens before the data is allowed to be inserted. Much more likely you'll get invalid datetimes when using a naked long
.
Finally, using a long
means that viewing your database via simple SQL (select * from table
) will produce illegible results.
I can't think of any outstanding reason personally, databases support DateTime's themselves, and storing them as a long you may end up shooting yourself in the foot. Let's say you need to be able to run a query "Get me all rows between 3 AM and 6 PM" - if you store them as ticks, you will need to convert back to a DateTime in the database.
Storing them as ticks may impede many other operations, such as grouping, sorting, filtering, etc.
If you have nuances with DateTimes in the database, such as TimeZone, it's strongly recommended to normalize the DateTime to a specific timezone, such as UTC. A lot of the problems that teams face with DateTime in the database is often due to unsanitary input, like not normalizing the TimeZone. Storing it as ticks will still have the same problem.
I guess that's down to personal preference. I always work with datetime types and don't have any bother with them.
If you store them as longs though semantically they are no longer dates. If you ever wanted to do a query to select all accounts added on a Friday (say) you would have to jump through several hoops to work that out.
In some cases, yes. Sql stores datetimes at a lower precision than DateTime. This means that a value persisted and retrieved may have a slightly different DateTime value from the original object, which might cause some issues with ordering or comparison.