Search code examples
vb.nettimezoneutc

offsetting a dateTime object ub VB.net


Suppose we need to get a fixed time such as 1600 eastern Time in local-time. I have found the following works fine

    Dim dtNow As DateTime = DateTime.Now
    Dim NYSEclose As DateTime
    Dim NYSEclose_localTime As DateTime
        NYSEclose = New DateTime(dtNow.Year, dtNow.Month, dtNow.Day, 16, 0, 0)
        Dim easternZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
        Dim utcTime As DateTime = TimeZoneInfo.ConvertTimeToUtc(NYSEclose, easternZone)
        NYSEclose_localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.Local)

Next, for testing purposes I would like to simulate the target time as one minute from now so expand the 4th line to

    If Debugger.IsAttached Then
        'NYSEclose = dtNow.AddMinutes(181)   'local Now is 180min behind ET plus 1
    Else
        NYSEclose = New DateTime(dtNow.Year, dtNow.Month, dtNow.Day, 16, 0, 0)
    endif

TWO questions:

  1. The function ConvertTimeToUtc fails: "The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local. (Parameter 'sourceTimeZone')" so .addMinutes is insufficient' Is there a way to do this right?

If I use the NEW construction method

NYSEclose = New DateTime(dtNow.Year, dtNow.Month, dtNow.Day, dtNow.hour+3, dtNow.minute+1, dtNow.second)

there is no error well but then one can't just add 3 hours and one minute unless I check all the way to the month to make sure it doesn't spill into the higher tier.

  1. The easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") is explicitly for Standard Time, will this fail during the Daylight time? I printed out the full list of timezones and none have daylight time, only standard time, perhaps that's a hint that EST in .net always means eastern time, can any expert confirm this suspicion?

Solution

  • Define explicitely the DateTime.Kind of the NYSEClose like this

    Dim c As DateTimeKind = DateTimeKind.Unspecified
            Dim b As Date = System.DateTime.SpecifyKind(Now, c)
            Dim easternZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
            Dim utcTime As DateTime = TimeZoneInfo.ConvertTimeToUtc(b, easternZone)