[vb.net] Getting Current time to display in Label. VB.net

I'm trying to build a Break tracker for work and I would like to get a button to display the Current Time in a label. I have tried multiple solutions and this is how far I have gotten.

Sub AddButtonClick(sender As Object, e As EventArgs)        
        Dim Start as Integer
        System.DateTime.Now = Start
        total.Text = Start      
End Sub

When I do this, I get the error that Property 'Now' is read only.

This question is related to vb.net

The answer is


Try This.....

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

try

total.Text = DateTime.Now.ToString()

or

Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()

You declare Start as an Integer, while you are trying to put a DateTime in it, which is not possible.


Use Date.Now instead of DateTime.Now


There are several problems here:

  • Your assignment is the wrong way round; you're trying to assign a value to DateTime.Now instead of Start
  • DateTime.Now is a value of type DateTime, not Integer, so the assignment wouldn't work anyway
  • There's no need to have the Start variable anyway; it's doing no good
  • total.Text is a property of type String - not DateTime or Integer

(Some of these would only show up at execution time unless you have Option Strict on, which you really should.)

You should use:

total.Text = DateTime.Now.ToString()

... possibly specifying a culture and/or format specifier if you want the result in a particular format.