NTPサーバから時間取得


NTPサーバから時間を取得するSNTPクライアントのサンプル。
VBでも意外と簡単に出来ますね。


Private Sub cmdGetTime_Click()
    Dim bytData(47) As Byte
    
    bytData(0) = &HB
    
    With wscSock
        .Close
        
        .Protocol = sckUDPProtocol
        .RemoteHost = txtServer.Text
        .RemotePort = 123
        .LocalPort = 1024
        Call .SendData(bytData())
    End With
End Sub

Private Sub wscSock_DataArrival(ByVal bytesTotal As Long)
    Dim A() As Byte
    Dim sVal As String
    Dim nTransmitTimeStampSeconds As Currency
    
    Dim nDays As Currency
    Dim nHours As Currency
    Dim nMinutes As Currency
    Dim nSecs As Currency
    
    Dim dteTime As Date
    
    Call wscSock.GetData(A())
    
    nTransmitTimeStampSeconds = CCur(A(40)) * 2 ^ (8 * 3) + CCur(A(41)) * 2 ^ (8 * 2) + CCur(A(42)) * 2 ^ 8 + CCur(A(43))
    nTransmitTimeStampSeconds = nTransmitTimeStampSeconds - 2208988800@
    
    nDays = nTransmitTimeStampSeconds \ 86400@
    nSecs = nTransmitTimeStampSeconds Mod 86400@
    
    nHours = nSecs \ 3600@
    nSecs = nSecs Mod 3600@
    
    nMinutes = nSecs \ 60@
    nSecs = nSecs Mod 60@
    dteTime = CDate(DateAdd("d", nDays, "1970/01/01") & " " & nHours & ":" & nMinutes & ":" & nSecs)
    txtTime.Text = Format(dteTime, "yyyy/mm/dd hh:nn:ss")
    
    dteTime = DateAdd("h", 9, dteTime)
    txtJapan.Text = Format(dteTime, "yyyy/mm/dd hh:nn:ss")
    
    Call wscSock.Close
End Sub


サンプル SNTPClient.ZIP