0

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?
1
  • Don't forget to consider Eastern Daylight Time, etc.
    – HardCode
    Commented May 22 at 15:09

1 Answer 1

0

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)
1
  • Thanks. I did not test your solution but it looks like it should do. I had already set up a half-assed method to check only on the overflow of minutes to hours, meaning I should avoid debugging after 10PM local time!
    – Ernesto
    Commented May 30 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.