How would I configure PetaPoco to create DateTimes with type DateTimeKind.Unspecified instead of UTC?

StackOverflow https://stackoverflow.com/questions/21285997

  •  01-10-2022
  •  | 
  •  

Question

I'm migrating a Subsonic project over to PetaPoco. When Subsonic pulls DateTime columns from the database, it's returning DateTime as DateTimeKind.Unspecified. When PetaPoco hydrates a POCO, it's setting DateTimes as UTC.

TopTen Software's website actually has a blog post mentioning this exact issue: http://www.toptensoftware.com/Articles/84/PetaPoco-Value-Conversions-and-UTC-Times

But there is an annotation stating the solution outlined is obsolete, and links to another article mentioning mappers. I can't figure out how to add mappers to my solution to resolve this issue.

No correct solution

OTHER TIPS

If you add this attribute to your POCO Object's DateTime Properties it will set the DateTimeKind to UTC for you (It doesn't do any conversions though).

[Column(ForceToUtc=true)]

Had to dig through the source to find this

To do the actual conversion to UTC, I modified PetaPoco:

PetaPoco.cs - Ln 3738

Change This:

return delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc); };

To This:

return delegate(object src) { return new DateTime(((DateTime)src).ToUniversalTime().Ticks, DateTimeKind.Utc); };

Just realized you were asking the opposite. I had to make these changes to get it to return proper UTC dates. You can modify PetaPoco to do the opposite with this code:

return delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Unspecified); };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top