Handling Dates and Times in Visual Basic .Net

The dates and times have an important role in our life and also in programs. Visual Basic .Net supports many functions to handle the dates and times in programs. VB.Net also provides a data type date to use dates.

Visual Basic Date and Time Properties

  • Date : To return the date only from the DateTime value.
  • Day : To return the day of month from the DateTime value.
  • Hour : To return the hour from the DateTime value.
  • Millisecond : To return the millisecond from the DateTime value.
  • Minute : To return the minute from the DateTime value.
  • Month : To return the month from the DateTime value.
  • DayOfWeek : To return the day of week from the DateTime value.
  • DayOfYear : To return the day of the year from the DateTime value.
  • Second : To return the second from the DateTime value.
  • Now : To return the current local date and time from the computer.
  • TimeOfDay : To return the time of day from the DateTime value.
  • Today : To return the current system date.
  • Year : To return the year from the DateTime value.
  • UtcNow : To return a DateTime value expressed as Coordinated Universal Time (UTC) from the local of the system.

Visual Basic Date and Time Methods

The following are the commonly used DateTime methods in VB.Net.

Public Function Add (value As TimeSpan) As DateTime

To add the value of the specified TimeSpan to the DateTime value.

Public Function AddDays ( value As Double) As DateTime

To add the specified number of days to the DateTime value.

Public Function AddHours (value As Double) As DateTime

To add the specified number of hours to the DateTime value.

Public Function AddMinutes (value As Double) As DateTime

To add the specified number of minutes to the DateTime value.

Public Function AddMonths (months As Integer) As DateTime

To add the specified number of months to the DateTime value.

Public Function AddSeconds (value As Double) As DateTime

To add the specified number of seconds to the DateTime value.

Public Function AddYears (value As Integer ) As DateTime

To add the specified number of years to the DateTime value.

Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer

To compare two time & date instances and returns the result in an integer value.

More Methods:

  • CompareTo
  • Equals
  • ToString

Example:

Module Module1

  Sub Main()
    Dim today As Date
    today = Date.Today
    Console.WriteLine(today)
    Console.ReadKey()
  End Sub

End Module

The above program will display the current date and time from the system.