January 25, 2021
Hot Topics:

Getting the Internet Time

  • By Karl Moore
  • Send Email »
  • More Articles »

We can turn the string returned by the Winsock control into a regular date with the help of a little function I made earlier:

  • Add the following function to your project:
Public Function FormatDateTime(NetTime As String) As Date    ' Takes the standard DDD MMM DD HH:MM:SS YYYY    ' format and changes it into a regular date!        Dim strDate As String    Dim strTime As String        ' Extract the date    strDate = Trim(Mid(NetTime, 4, 7)) & " " & _        Trim(Mid(NetTime, 21))        ' Extract the time    strTime = Trim(Mid(NetTime, 12, 9))        ' Check the extracts are suitable date    ' and times - then convert using CDate    If IsDate(strDate) And IsDate(strTime) Then        FormatDateTime = CDate(strDate & " " & strTime)    Else        ' If unsuitable, set FormatDateTime to system        ' clock date and time        FormatDateTime = Now    End IfEnd Function

Now let's alter the old code to use this new function:

  • Alter the code behind the DataArrival event to:
Dim strData As StringDim datDate As DateWinsock1.GetData strData, vbStringdatDate = FormatDateTime(strData)MsgBox ("The current date and time is:" & _Format(datDate, "dddd mmmm dd yyyy hh:mm:ss"))Winsock1.Close

This code uses the new FormatDateTime function to extract a real date and time from the returned string. This is then displayed in a message box, after being neatly formatted by the Format command.

  • Press F5 and test your application

And that's about it! You've learned virtually all there is to know about extracting the most up-to-date time from some of the world's most powerful computers.

But what can you do with this newfound knowledge? Well, some need the current date and time from an authenticated source to validate time-critical information, such as medical data or record accurate order times.

However by far and away the most common use is to ensure both yours and your users computer clocks are kept from losing those extra few seconds each and every day. In fact, one guy even built a freeware program that automatically does this every couple o' hours.

Yet that leads us to one final question. We know how to retrieve the most accurate date and time. But how do you set the computer clock?

Page 4 of 6

This article was originally published on November 20, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date