Working with Date and Time


This lesson will explain how to set date and time and how to display current date and time in VB6 code. This lesson does not dive into depth but gives you the basic concept of date and time in Visual Basic 6.

So here I'll explain only four properties related to time and date. They are Date, Time, Now and Timer. And lastly, I'll explain about the Date data type.


Refer to lesson 35: Formatting functions to learn about formatting date-time values. 




Displaying current date and time

Using Date and Time properties, you can set or display the system's current date and time respectively. The Time property displays both, current date and time.

Note: Date, Time and Now are not functions, they are properties.


Example:

'Displays current time
Print Time             '12:53:12 PM

'Displays current date
Print Date             '04-09-2012

'Displays current date,time
Print Now              '04-09-2012  12:53:12 PM



Setting the system date and time

You can set the current date and time of your computer in Visual Basic code.

Example: On clicking the CommandButton, the system date and time are changed.

Private Sub cmdSetDateTime_Click()
    Date = "04-10-2012"
    Time = "02:38:00 PM"
End Sub

The Timer property

The Timer property returns the number of seconds elapsed 
since midnight.

Example: 
Private Sub cmdShow_Click()
    MsgBox Timer & " seconds elapsed since midnight"
End Sub

Output: 

Program using the timer property



While working with date-time values in VB6, the Date data type is useful. Learn about data types in the following lessons:

Using the Date data type

Dim d As Date
d = Now
Print d

Declare a variable as Date, then you can assign any date value to this variable. The date data type lets you work with date-time values most efficiently.

Visual Basic gives you many properties and methods to handle date-time values. All of them will be covered later.