Reputation: 952
I want to save a DateTimeOffset in my database as the timezone I provide
When I get a date from the frontend of my application, it is passed in as UTC time.
In the database, I dont want this: 2020-06-24 20:00:00.000000 +00:00
, I want this: 2020-06-24 16:00:00.000000 -04:00
The reason I want to do this is because we have some legacy functions and stored procedures in SQL Server that don't consider the timezone, but we still want to look things up on the right date. Ex: an event occurred at 6/25 at 11PM EST, would be currently saved as 6/26 3AM UTC. Now if we look up all events for 6/25, the 6/25 11PM event wouldn't show up. This is why I want to save it as EST on the database.
I have looked at TimeZoneInfo.ConvertTime
but that only takes in and returns a DateTime, not a DateTimeOffset
I really am looking for something that is like DateTimeOffset.ConvertTo(TimeZoneInfo)
, but I have yet to find a good solution that also takes care of DST
Upvotes: 0
Views: 2014
Reputation: 952
This is how I ended up solving this problem. This will convert it to the proper timezone, in this case
private DateTimeOffset ChangeTimezone(DateTimeOffset originalTime)
{
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time");
return originalTime.ToOffset(tzi.GetUtcOffset(originalTime));
}
In my tests, this preserves DST too. For example, the offset would be -5 for Central Time and -6 during daylight savings time.
Upvotes: 1