Search code examples
winapivb6systemtimefiletime

Why does my SystemTimeToFileTime return a result which is off by 5 hours?


It would make sense if I was in a ±5 hour timezone, but I'm in GMT -06:00, so I'm not sure if timezones are my problem or if it's something else. Here is my code I'm using:

Private Sub SetFileTimes(file As String, Optional creationTime As Date, Optional accessTime As Date, Optional writeTime As Date)
    Dim handle As Long
    Dim sysCreationTime As FileTime, sysAccessTime As FileTime, sysWriteTime As FileTime
    Dim SECURITY_ATTRIBUTES As SecurityAttributes
    SECURITY_ATTRIBUTES.nLength = Len(SECURITY_ATTRIBUTES)
    SECURITY_ATTRIBUTES.lpSecurityDescriptor = 0
    SECURITY_ATTRIBUTES.bInheritHandle = False
    handle = CreateFile(file & Chr$(0), GENERIC_READ Or GENERIC_WRITE, FILE_SHARE_READ Or FILE_SHARE_WRITE, SECURITY_ATTRIBUTES, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0&)
    Debug.Assert handle <> -1
    GetFileTime handle, sysCreationTime, sysAccessTime, sysWriteTime

    If creationTime <> 0 Then
        SystemTimeToFileTime GetSystemTime(creationTime), sysCreationTime
    End If
    If accessTime <> 0 Then
        SystemTimeToFileTime GetSystemTime(accessTime), sysAccessTime
    End If
    If writeTime <> 0 Then
        SystemTimeToFileTime GetSystemTime(writeTime), sysWriteTime
    End If

    SetFileTime handle, sysCreationTime, sysAccessTime, sysWriteTime
    CloseHandle handle
End Sub

Private Function GetSystemTime(datetime As Date) As SystemTime
    GetSystemTime.Year = Year(datetime)
    GetSystemTime.Month = Month(datetime)
    GetSystemTime.Day = Day(datetime)
    GetSystemTime.Hour = Hour(datetime)
    GetSystemTime.Minute = Minute(datetime)
    GetSystemTime.Second = Second(datetime)
    GetSystemTime.Milliseconds = 0
End Function

The function works, but all of my times are 5 hours early. (I.E. If I try and set the date to 10am, it will set it to 5am instead.) The default times (ones I do not specify) do not change, as expected. While debugging, I can see that SystemTimeToFileTime is returning a value less than it should be. What can I do to fix this?


Solution

  • During daylight savings time, Chicago (usually GMT-06) is GMT-05.

    Edit: Added link to FileTimeToLocalTime.