Handling Dates and Times in VB.net

By: Steven Holzner Emailed: 1787 times Printed: 2623 times    

One of the biggest headaches a programmer can have is working with dates. Handling hours, minutes, and seconds can be as bad as working with shillings, pence, and pounds. Fortunately, Visual Basic has a number of date and time handling functions, which appear in Table below-you can even add or subtract dates using those functions. VB6 programmers will notice a number of new properties in this table.

Visual Basic date and time properties.

To do this

Use this

Get the current date or time

Today, Now, TimeofDay, DateString, TimeString

Perform date calculations

DateAdd, DateDiff, DatePart

Return a date

DateSerial, DateValue

Return a time

TimeSerial, TimeValue

Set the date or time

Today, TimeofDay

Time a process

Timer

Here's an example in which I'm adding 22 months to 12/31/2001 using DateAdd-you might note in particular that you can assign dates of the format 12/31/2001 to variables of the Date type if you enclose them inside # symbols:

Imports System.Math
Module Module1
    Sub Main()
        Dim FirstDate As Date
        FirstDate = #12/31/2001#
        System.Console.WriteLine("New date: " & DateAdd_
        (DateInterval.Month, 22, FirstDate))
    End Sub
End Module

Here's what you see when you run this code:

New date: 10/31/2003
Press any key to continue

There's something else you should know-the Format function makes it easy to format dates into strings, including times. For easy reference, see Table 2.11, which shows some ways to display the date and time in a string-note how many ways there are to do this.

Table 2.11: Using Format to display dates and times.

Format Expression

Yields this

Format(Now, "M-d-yy")

"1-1-03"

Format(Now, "M/d/yy")

"1/1/03"

Format(Now, "MM - dd - yy")

"01 /01 / 03"

Format(Now, "ddd, MMMM d, yyy")

"Friday, January 1, 2003"

Format(Now, "d MMM, yyy")

"1 Jan, 2003"

Format(Now, "hh:mm:ss MM/dd/yy")

"01:00:00 01/01/03"

Format(Now, "hh:mm:ss tt MM-dd-yy")

"01:00:00 AM 01-01-03"

You can also compare dates and times directly. For example, here's how you loop until the current time (returned as a string by TimeString) exceeds a certain time; when the time is up, the code beeps using the Visual Basic Beep function:

While TimeString < "15:45:00"
End While
Beep()
Tip 

Don't use the above code snippet for more than an example of how to compare times! The eternal looping while waiting for something to happen is a bad idea in Windows, because your program monopolizes a lot of resources that way. Instead, set up a Visual Basic Timer and have a procedure called, say, every second.

Most Viewed Articles (in VB.net )

Latest Articles (in VB.net)

Comment on this tutorial