Home > Software design >  EF Core DateTimeToTicksConverter vs long-Conversion
EF Core DateTimeToTicksConverter vs long-Conversion

Time:08-31

I was checking the official documentation for possible converters of the DateTime data type and was wondering what's the difference between .HasConversion<long>() and .HasConversion<DateTimeToTicksConverter>(), since both are stored as "long" 64 bit integer in the database.

The documentation for .HasConversion<long>() says:

Encoded date/time preserving DateTime.Kind

And the documentation for .HasConversion<DateTimeToTicksConverter>() just says one word:

Ticks

Can someone please clarify the difference between those two conversions?

CodePudding user response:

The documentation link contains a list of built-in converters where you can see the following

The documentation for HasConversion<long> refers to the first one (DateTimeToBinaryConverter) which in turn

Converts DateTime using ToBinary(). This will preserve the DateTimeKind.

For the opposite conversion I assume they are using FromBinary.

The other one (DateTimeToTicksConverter) is instead using Ticks property and corresponding DateTime constructor.

CodePudding user response:

The answer this, you must first understand what a "tick" is. It is actually explained on the Microsoft documentation for the System.DateTime.Tick property

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond (see TicksPerMillisecond) and 10 million ticks in a second. The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 in the Gregorian calendar, which represents MinValue. It does not include the number of ticks that are attributable to leap seconds. If the DateTime object has its Kind property set to Local, its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the local time as specified by the current time zone setting. If the DateTime object has its Kind property set to Utc, its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the Coordinated Universal Time. If the DateTime object has its Kind property set to Unspecified, its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the unknown time zone.

Which implies that the DateTime.Kind information is lost when converting to- and from "ticks"

Apparently the EF Core team has devised a custom conversion to- and from long that does keep the DateTime.Kind information. It might be stored in the two upper bits of the 64, for example. There doesn't seem to be detailed documentation on it. It's likely not compatible with other date-time types, while "ticks" are easi(er) to convert. See "system time" on Wikipedia.

  • Related