VB6 Tutorial 38: Working with the Date and Time

By | 2018-04-23

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.

In this lesson we’ll cover Date, Time, Now, Timer, and the Date data type. To learn more about formatting strings in a date format, seeĀ VB6 Tutorial 35: Formatting Functions.

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.

QuickHint:

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 and 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

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. As we go through the rest of the lessons in this tutorial, each one will be covered along the way.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.