Interactive digital clock with VB6 and VB.NET code examples
This interactive digital clock demonstrates how a simple Visual Basic application can be created with minimal code. The timer updates the display every second, just like in VB6 and VB.NET applications.
A digital clock in Visual Basic can be created with just a few lines of code. The key components are:
In both VB6 and VB.NET, you would:
In VB6, creating a digital clock is straightforward with the Timer control.
' Digital Clock in VB6 Private Sub Form_Load() ' Set timer interval to 1000ms (1 second) Timer1.Interval = 1000 ' Set initial time UpdateTime End Sub Private Sub Timer1_Timer() ' Update time every second UpdateTime End Sub Private Sub UpdateTime() ' Display time in 12-hour format with AM/PM lblTime.Caption = Format(Time, "hh:mm:ss AMPM") ' Display date lblDate.Caption = Format(Date, "dddd, mmmm dd, yyyy") End Sub
VB.NET uses a similar approach but with .NET framework classes.
' Digital Clock in VB.NET Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Set timer interval to 1000ms (1 second) Timer1.Interval = 1000 ' Start the timer Timer1.Start() ' Set initial time UpdateTime() End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick ' Update time every second UpdateTime() End Sub Private Sub UpdateTime() ' Display time in 12-hour format with AM/PM lblTime.Text = DateTime.Now.ToString("hh:mm:ss tt") ' Display date lblDate.Text = DateTime.Now.ToString("dddd, MMMM dd, yyyy") End Sub
Time
and Date
functionsTimer1_Timer()
Format(expression, format)
DateTime.Now
propertyTimer1_Tick()
ToString()
methodExtend the digital clock with these features:
Advanced Challenge: Build an analog clock that updates in real-time using graphics methods.