Introduction
This Small application shows how to display the Server's date and time in your application.
Background
The requirement is to display the database servers Current System Date and Time in the client application. When the client application starts it fetches the Current Date and Time on the Remote server(Database Server) and keeps incrementing it by one second using a Timer.
Using the code
Code for the ServerDateTime Class:
Imports System.Data
Imports System.Data.SqlClient
Public Class ServerDateTime
Public dtServerDateTime As DateTime
Private Shared tmrLocalTimer As New System.Windows.Forms.Timer()
Dim IsFirstTime As Boolean = True
Public Sub TimerEventProcessor(ByVal myObject As Object, ByVal myEventArgs As EventArgs)
If IsFirstTime = True Then
Dim cmd As SqlCommand
Dim tmpConnection As SqlConnection
Dim strConnectionString As String
Try
strConnectionString = System.Configuration.ConfigurationManager.AppSettings("ServerConnectionString")
tmpConnection = New SqlConnection(strConnectionString)
tmpConnection.Open()
cmd = New SqlCommand("Select GetDate()", tmpConnection)
dtServerDateTime = cmd.ExecuteScalar
GetServerDateAndTime.lServerDateTime.Text = Format(dtServerDateTime, "dd/MM/yyyy hh:mm:ss tt")
IsFirstTime = False
Catch ex As Exception
MsgBox(ex.Message)
Finally
If tmpConnection.State = ConnectionState.Open Then
cmd = Nothing
tmpConnection.Close()
End If
End Try
Else
dtServerDateTime = DateAdd(DateInterval.Second, 1, dtServerDateTime)
End If
tmrLocalTimer.Enabled = True
GetServerDateAndTime.lServerDateTime.Text = Format(dtServerDateTime, "dd/MM/yyyy hh:mm:ss tt")
End Sub
Public Sub GetServerDateTime()
AddHandler tmrLocalTimer.Tick, AddressOf TimerEventProcessor
tmrLocalTimer.Interval = 1000
tmrLocalTimer.Start()
End Sub
End Class