0

We are saving all dates in UTC in our database and also saving offset for each user.

We are converting to localtime by following function:

 Private Function ConvertToLocalDateTime(ByVal utcOffset As Integer?, ByVal DateToConvert As DateTime?) As DateTime?

        getdatetime = DateToConvert.Value.AddHours(utcOffset)

        If getdatetime.IsDaylightSavingTime Then
            getdatetime.AddHours(-1)
        End If

        Return getdatetime
    End Function

But still dates are 1 or 2 hours off.

How can we convert correctly to localtime from utcoffset also taking care of daylight saving?

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
skcrpk
  • 558
  • 5
  • 18
  • See https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tolocaltime?view=netframework-4.8 . *The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object. * – 3Dave Sep 11 '19 at 14:32
  • 1
    It's not clear to me why you take a UTC offset as a parameter. Instead, you should take a TimeZoneInfo, as that knows the time zone rules to apply in any situation. If you've only recorded the UTC offset for your users at a particular point in time, you don't have enough information. – Jon Skeet Sep 11 '19 at 14:32

1 Answers1

1

As long as the Kind property on DateToConvert is set properly to Utc, then you can just call DateToConvert.ToLocalTime().

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84