1

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.

japes Sophey
  • 487
  • 3
  • 8
  • 26

1 Answers1

5

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

Jonathan
  • 4,916
  • 2
  • 20
  • 37
  • Will this work even though the value I'm receiving does not contain a specified kind of UTC. Once the date-time value is stored in SQL, the system does not know that it's kind is UTC. – japes Sophey Aug 25 '20 at 15:51
  • When you inspect the `DateTime` value, what is its `Kind`? The docs say it must be 'unspecified' or 'utc' for `ConvertTimeFromUtc` to function correctly – Jonathan Aug 25 '20 at 16:02
  • 1
    If the `kind` is not 'unspecified' or 'utc' you have to use `DateTime.SpecifyKind()` to convert it – Jonathan Aug 25 '20 at 16:04