I am using NodaTime and Entity Framework Core in my application. I am using AutoMapper to convert from my models (which use LocalTime) to my entities (which use Timespan which is mapped to Time in Sql Server). I am doing it this way to avoid the pitfalls of EF ValueConversions.
When going from entities to models (i.e. Timespan to LocalTime), I found the "official" way of doing it (https://github.com/nodatime/nodatime/issues/148):
LocalTime.FromTicksSinceMidnight(timespan.Ticks)
But, going from models to entities (i.e. LocalTime to Timespan), I am not sure what the best way is. Dates and times seem too tricky to just grab the hours, minutes, etc like:
new TimeSpan(localTime.Hour, localTime.Minute, localTime.Second, localTime.Second, localTime.Millisecond)
Should I utilize ticks like when going from LocalTime to Timespan?
TimeSpan.FromTicks(localTime.TickOfSecond)
Converting from LocalTime
to TimeSpan
, you can indeed use ticks - but you want TickOfDay
:
TimeSpan timeSinceMidnight = TimeSpan.FromTicks(localTime.TickOfDay);