Convert between UTC time and local time

Started by nandagopal, Nov 17, 2008, 07:26 PM

Previous topic - Next topic

nandagopal

Copy the date/time elements into a SYSTEMTIME structure.

Use the SystemTimeToFileTime API function to convert the SYSTEMTIME into a FILETIME structure.

Use the LocalFileTimeToFileTime API function to convert from the local time to UTC time.

Use the FileTimeToSystemTime API function to convert the UTC time into a SYSTEMTIME structure.

Pull the fields out of the SYSTEMTIME to get the Visual Basic date format.

Reverse the steps to go from a UTC time to the local file system time.


' Convert a Date into a SYSTEMTIME.
Private Sub DateToSystemTime(ByVal the_date As Date, ByRef _
    system_time As SYSTEMTIME)
    With system_time
        .wYear = Year(the_date)
        .wMonth = Month(the_date)
        .wDay = Day(the_date)
        .wHour = Hour(the_date)
        .wMinute = Minute(the_date)
        .wSecond = Second(the_date)
    End With
End Sub

' Convert a SYSTEMTIME into a Date.
Private Sub SystemTimeToDate(system_time As SYSTEMTIME, _
    ByRef the_date As Date)
    With system_time
        the_date = DateSerial(.wYear, .wMonth, .wDay) + _
                   TimeSerial(.wHour, .wMinute, .wSecond)
    End With
End Sub

' Convert a local time to UTC.
Private Function LocalTimeToUTC(ByVal the_date As Date) As _
    Date
Dim system_time As SYSTEMTIME
Dim local_file_time As FILETIME
Dim utc_file_time As FILETIME

    ' Convert it into a SYSTEMTIME.
    DateToSystemTime the_date, system_time

    ' Convert it to a FILETIME.
    SystemTimeToFileTime system_time, local_file_time

    ' Convert it to a UTC time.
    LocalFileTimeToFileTime local_file_time, utc_file_time

    ' Convert it to a SYSTEMTIME.
    FileTimeToSystemTime utc_file_time, system_time

    ' Convert it to a Date.
    SystemTimeToDate system_time, the_date

    LocalTimeToUTC = the_date
End Function

' Convert a UTC time into local time.
Private Function UTCToLocalTime(ByVal the_date As Date) As _
    Date
Dim system_time As SYSTEMTIME
Dim local_file_time As FILETIME
Dim utc_file_time As FILETIME

    ' Convert it into a SYSTEMTIME.
    DateToSystemTime the_date, system_time

    ' Convert it to a UTC time.
    SystemTimeToFileTime system_time, utc_file_time

    ' Convert it to a FILETIME.
    FileTimeToLocalFileTime utc_file_time, local_file_time

    ' Convert it to a SYSTEMTIME.
    FileTimeToSystemTime local_file_time, system_time

    ' Convert it to a Date.
    SystemTimeToDate system_time, the_date

    UTCToLocalTime = the_date
End Function