Reputation: 495
I'm storing a date-time in SQL which is retrieved from an Azure server which is in UTC.
When I come to retrieve this date-time from SQL, the date-time kind is unspecified ...
In the UK, we are currently in BST, how can I convert the date-time I received from SQL to BST or GMT depending on the time of year?
My test/production servers are in Azure which runs on UTC.
Answer
Thanks to @jonathon I came up with the following extension method that solves my issue.
public static DateTime CovertDateTimeToDateTimeGmt(this DateTime source)
{
var sourceUtc = DateTime.SpecifyKind(source, DateTimeKind.Utc);
var destinationTimezoneId = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
var sourceLocalTime = TimeZoneInfo.ConvertTimeFromUtc(sourceUtc, destinationTimezoneId);
return sourceLocalTime;
}
Because the date-time I was receiving from SQL did not specify a date-time kind, I firstly converted this a new date-time specifying the kind.
Upvotes: 1
Views: 12116
Reputation: 5018
Use ConvertTimeFromUtc
and specify the time zone to convert into. It should take into account daylight savings time as necessary.
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
See: https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.converttimefromutc?view=netcore-3.1
and
https://learn.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones
Upvotes: 5