Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

VB.Net - Date and time


May 13, 2021 vb.net


Table of contents


Most of the software you write needs to implement some form of date function, returning the current date and time. D ates are part of everyday life, and using them makes work easy and doesn't require much thought. V b. N et also provides powerful date arithmetic tools to make it easy to operate dates.


The date data type contains date values, time values, or date and time values. D ate's default value is 0:00:00 (midnight) on January 1, 0001. E quivalent. T he NET data type is System.DateTime.


The DateTime structure represents the instant time, typically the day of the date and time

'Declaration
<SerializableAttribute> _
Public Structure DateTime _
	Implements IComparable, IFormattable, IConvertible, ISerializable,  
	IComparable(Of DateTime), IEquatable(Of DateTime)

You can also get the current date and time from the DateAndTime class.


The DateAndTime module contains procedures and properties used in date and time operations.

'Declaration
<StandardModuleAttribute> _
Public NotInheritable Class DateAndTime

Attention:

Both the DateTime structure and the DateAndTime module contain properties such as Now and Today, so beginners are often confused. The DateAndTime class belongs to the Microsoft.VisualBasic namespace, and the DateTime structure belongs to the System namespace.


So using later will help you port your code to another one. N et language, such as C. H owever, the DateAndTime class/module contains all the old date functions available in Visual Basic.

The properties and methods of the DateTime structure

The following table lists some common properties of dateTime structures:

S.N Property Describe
1 Date Gets the date component of this instance.
Gets the date component for this instance.
2 Day Gets the day of the month represented by this instance.
Gets the day of the month that this instance represents.
3 DayOfWeek Gets the day of the week represented by this instance.
Gets the day of the week represented by this instance.
4 DayOfYear Gets the day of the year represented by this instance.
Gets the day of the year that this instance represents.
5 Hour Gets the hour component of the date represented by this instance.
Gets the hour component of the date represented by this instance.
6 Kind Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. G
Gets a value that indicates whether the time represented by this instance is based on local time, coordinated world time (UTC), or neither.
7 Millisecond Gets the milliseconds component of the date represented by this instance.
Gets the millisecond component of the date represented by this instance.
8 Minute Gets the minute component of the date represented by this instance.
Gets the minute weight of the date represented by this instance.
9 Month Gets the month component of the date represented by this instance.
Gets the month of the date represented by this instance.
10 Now Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
Gets the DateTime object, which is set to the current date and time on this computer, in local time.
11 Second Gets the seconds component of the date represented by this instance.
Gets the second component of the date represented by this instance.
12 Ticks Gets the number of ticks that represent the date and time of this instance.
Gets the number of scales that represent the date and time of this instance.
13 TimeOfDay Gets the time of day for this instance.
The time at which this instance was obtained.
14 Today Gets the current date.
Gets the current date.
15 UtcNow Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
Gets the DateTime object that is set to the current date and time on this computer to coordinate the world time (UTC) detation.
16 Year Gets the year component of the date represented by this instance.
Gets the year component for the date represented by this instance.

The following table lists some common ways to structure DateTime:

SN Method name and description
1

Public Function Add (value As TimeSpan) As DateTime
The public function Add (value as a time span) As DateTime

Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

2

Public Function AddDays ( value As Double) As DateTime
The common function AddDays (value is double) As DateTime

Returns a new DateTime that adds the specified number of days to the value of this instance.

3

Public Function AddHours (value As Double) As DateTime
The common function AddHours (value is double) As DateTime

Returns a new DateTime that adds the specified number of hours to the value of this instance.

4

Public Function AddMinutes (value As Double) As DateTime
The common function AddMinutes (value is double) As DateTime

Returns a new DateTime that adds the specified number of minutes to the value of this instance.

5

Public Function AddMonths (months As Integer) As DateTime
The public function AddMonths (month as an integer) As DateTime

Returns a new DateTime that adds the specified number of months to the value of this instance.

6

Public Function AddSeconds (value As Double) As DateTime
The common function AddSeconds (value is double) As DateTime

Returns a new DateTime that adds the specified number of seconds to the value of this instance.

7

Public Function AddYears (value As Integer ) As DateTime
The common function AddYears (value integer) As DateTime

Returns a new DateTime that adds the specified number of years to the value of this instance.

8

Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer
Public share function comparison (T1 as date time, T2 as DATETIME) As Integer

Compare the two DateTime instances and return an integer indicating whether the first instance is earlier than the second instance or later than the second instance.

9

Public Function CompareTo (value As DateTime) As Integer
The common function CompanyTo (value DATETIME) As Integer

Compare the value of this instance with the specified DateTime value and return an integer indicating whether the instance is earlier than, equal to, or later than the specified DateTime value.

10

Public Function Equals (value As DateTime) As Boolean
The common function is equal to (valued DATETIME) Boo Aslean

Returns a value that indicates whether the value of this instance is equal to the value of the specified DateTime instance.

11

Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean
The common sharing function is equal to (T1 as the date time, T2 as DATETIME) as Boolean

Returns a value that indicates whether the two DateTime instances have the same date and time values.

12

Public Overrides Function ToString As String
Public override function ToString As String

Converts the value of the current DateTime object to its equivalent string representation.

The methods listed above are not exhaustive, please visit Microsoft's documentation for a complete list of the methods and properties of the DateTime structure.


Create a DateTime object

You can create a DateTime object in one of the following ways:

  • By calling a DateTime constructor from any of the overloaded DateTime constructors. Call the DateTime constructor from any overloaded DateTime constructor.

  • By assigning the DateTime object a date and time value returned by a property or method.
    The date and time value returned by assigning properties or methods to the DateTime object.

  • By parsing the string representation of a date and time value.
    Represented by a string that resolves date and time values.

  • By calling the DateTime structure's implicit default constructor.
    By calling the implicit default constructor of the DateTime structure.


The following example illustrates this:

Module Module1
   Sub Main()
      'DateTime constructor: parameters year, month, day, hour, min, sec
      Dim date1 As New Date(2012, 12, 16, 12, 0, 0)
      'initializes a new DateTime value
      Dim date2 As Date = #12/16/2012 12:00:52 AM#
      'using properties
      Dim date3 As Date = Date.Now
      Dim date4 As Date = Date.UtcNow
      Dim date5 As Date = Date.Today
      Console.WriteLine(date1)
      Console.WriteLine(date2)
      Console.WriteLine(date3)
      Console.WriteLine(date4)
      Console.WriteLine(date5)
      Console.ReadKey()
   End Sub
End Module


When the above code is compiled and executed, it produces the following results:

12/16/2012 12:00:00 PM
12/16/2012 12:00:52 PM
12/12/2012 10:22:50 PM
12/12/2012 12:00:00 PM


Get the current date and time:

The following program demonstrates how to get VB.Net date and time in the application:


Current time:

Module dateNtime
   Sub Main()
      Console.Write("Current Time: ")
      Console.WriteLine(Now.ToLongTimeString)
      Console.ReadKey()
   End Sub
End Module


When the above code is compiled and executed, it produces the following results:

Current Time: 11 :05 :32 AM


Current date:

Module dateNtime
   Sub Main()
      Console.WriteLine("Current Date: ")
      Dim dt As Date = Today
      Console.WriteLine("Today is: {0}", dt)
      Console.ReadKey()
   End Sub
End Module


When the above code is compiled and executed, it produces the following results:

Today is: 12/11/2012 12:00:00 AM


Format the date

The literal value of the date should be enclosed with a hash symbol and specified in M/d/yyyy format, for example, s12/16/2012. Otherwise, your code may change, depending on the environment in which you are running your application.

For example, you have specified a date literal value of 2/6/2012 for the date of February 6, 2012. T his is true for language environments that use the mm/dd/yy format. H owever, in a language using the dd/mm/yyyy format, your text will compile to June 2, 2012. If the language environment uses another format, such as yyyyy / mm / dd, the text will not work and cause a compiler error.

To convert Date literal values to a format or custom format for your locale, use the Format class's Form function to specify a predefined or user-defined date format.

The following example demonstrates this.

Module dateNtime
   Sub Main()
      Console.WriteLine("India Wins Freedom: ")
      Dim independenceDay As New Date(1947, 8, 15, 0, 0, 0)
      ' Use format specifiers to control the date display.
      Console.WriteLine(" Format 'd:' " & independenceDay.ToString("d"))
      Console.WriteLine(" Format 'D:' " & independenceDay.ToString("D"))
      Console.WriteLine(" Format 't:' " & independenceDay.ToString("t"))
      Console.WriteLine(" Format 'T:' " & independenceDay.ToString("T"))
      Console.WriteLine(" Format 'f:' " & independenceDay.ToString("f"))
      Console.WriteLine(" Format 'F:' " & independenceDay.ToString("F"))
      Console.WriteLine(" Format 'g:' " & independenceDay.ToString("g"))
      Console.WriteLine(" Format 'G:' " & independenceDay.ToString("G"))
      Console.WriteLine(" Format 'M:' " & independenceDay.ToString("M"))
      Console.WriteLine(" Format 'R:' " & independenceDay.ToString("R"))
      Console.WriteLine(" Format 'y:' " & independenceDay.ToString("y"))
      Console.ReadKey()
   End Sub
End Module


When the above code is compiled and executed, it produces the following results:

India Wins Freedom:
Format 'd:' 8/15/1947
Format 'D:' Friday, August 15, 1947
Format 't:' 12:00 AM
Format 'T:' 12:00:00 AM
Format 'f:' Friday, August 15, 1947 12:00 AM
Format 'F:' Friday, August 15, 1947 12:00:00 AM
Format 'g:' 8/15/1947 12:00 AM
Format 'G:' 8/15/1947 12:00:00 AM
Format 'M:' 8/15/1947 August 15
Format 'R:' Fri, 15 August 1947 00:00:00 GMT
Format 'y:' August, 1947


Predefined date/time format

The following table lists predefined date and time format names. You can use these names as style parameters for Format functions:

Format Describe
General Date, or G

Displays a date and/or time. For example, 1/12/2012 07:07:30 AM

Show date and/or time. For example, 1/12/2012 07:07:30 AM.

Long Date,Medium Date, or D

Displays a date according to your current culture's long date format. For example, Sunday, December 16,2012 .

Show dates based on the long date format of your current region. For example, Sunday, 16 December 2012

Short Date, or d

Displays a date using your current culture's short date format. For example, 12/12/2012

Displays the date in the current region short date format. For example, 12/12/2012.

Long Time,Medium Time, orT

Displays a time using your current culture's long time format; t ypically includes hours, minutes, seconds. For example, 01:07:30 AM

Display time in a long format for your current area; U sually includes hours, minutes, and seconds. For example, 01:07:30 AM.

Short Time or t

Displays a time using your current culture's short time format. For example, 11:07 AM

Displays the time in a short format for the current region. For example, 11:07 AM.

F

Displays the long date and short time according to your current culture's format. For example, Sunday, December 16, 2012 12:15 AM

Show long dates and short periods of time based on your current zone format. For example, sunday, December 16, 2012, at 12:15 a.m.

F

Displays the long date and long time according to your current culture's format. For example, Sunday, December 16, 2012 12:15:31 AM

Show long dates and long periods based on your current zone format. For example, on Sunday, December 16, 2012, 12:15:31 AM.

G

Displays the short date and short time according to your current culture's format. For example, 12/16/2012 12:15 AM

Show short dates and short times based on your current zone format. For example, 12/16/2012 12:15 AM.

Mm

Displays the month and the day of a date. For example, December 16

Displays the month and date of the date. For example, on December 16th.

R, r

Formats the date according to the RFC1123Pattern property

Format the date according to the RFC1123Pattern property.

s

Formats the date and time as a sortable index. For example, 2012-12-16T12:07:31

Format dates and times as sortable indexes. For example, 2012-12-16T12:07:31.

u

Formats the date and time as a GMT sortable index. For example, 2012-12-16 12:15:31Z

Format the date and time as a GMT sortable index. For example, 2012-12-16 12:15:31Z.

U

Formats the date and time with the long date and long time as GMT. For example, Sunday, December 16, 2012 6:07:31 PM

Format dates and times as long and long, in GMT format. For example, sunday, December 16, 2012 at 6:07:31 p.m.

Y, y

Formats the date as the year and month. For example, December, 2012

Format the date to year and month. For example, in December 2012.


For other formats, such as user-defined formats, see the Microsoft documentation.


Properties and methods for the DateAndTime class

The following table lists some common properties of the DateAndTime class:

SN Property Describe
1 Date
Returns or sets a String value representing the current date according to your system.
Returns or sets string values based on the system's representation of the current date.
2 Now
Returns a Date value containing the current date and time according to your system.
Returns a date value that contains the current date and time of the system.
3 TimeOfDay Returns or sets a Date value containing the current time of day according to your system.
Return or set the date value based on the current time of the day that your system contains.
4 Timer
Returns a Double value representing the number of seconds elapsed since midnight.
Returns a Double value for the number of seconds that have passed since midnight.
5 TimeString Returns or sets a String value representing the current time of day according to your system.
Return or set a string value based on the current time of day that your system represents.
6 Today
Gets the current date.
Gets the current date.


The following table lists some common methods for DateAndTime classes:

SN Method name and description
1

Public Shared Function DateAdd (Interval As DateInterval, Number As Double, DateValue As DateTime) As DateTime
The common sharing function uses DateAdd (dated Interval at intervals, with the number DOUBLE, then DateValue as DATETIME) as DATETIME

Returns the Date value that contains the date and time values for which the specified interval has been added.

2

Public Shared Function DateAdd (Interval As String,Number As Double,DateValue As Object ) As DateTime
The common sharing function uses DateAdd (the interval is a string, the number is DOUBLE, then DateValue is the object) as DATETIME

Returns the Date value that contains the date and time values for which the specified interval has been added.

3

Public Shared Function DateDiff (Interval As DateInterval, Date1 As DateTime, Date2 As DateTime, DayOfWeek As FirstDayOfWeek, WeekOfYear As FirstWeekOfYear ) As Long
The common sharing function DateDiff (date 1 is DATETIME, date 2 is DATETIME, week as Firstdayofweek, WEEKOFYEAR as FirstWeekOfYear) As Long

Returns a long, integer value that specifies the number of time intervals between two date values.

4

Public Shared Function DatePart (Interval As DateInterval, DateValue As DateTime, FirstDayOfWeekValue As FirstDayOfWeek, FirstWeekOfYearValue As FirstWeekOfYear ) As Integer
The common sharing function DATEPART (dated Date Interval, then DateValue for DATETIME, FirstDayOfWeekValue as FirstDayofweek, FirstWeekOfYearValue as FirstWeekOfYear) as the integer

Returns the integer value of the specified component that contains the given Date value.

5

Public Shared Function Day (DateValue As DateTime) As Integer
The public sharing function Day (DateValue will act as DATETIME) as an integer

Returns integer values from 1 to 31, representing one day of the month.

6 Public Shared Function Hour (TimeValue As DateTime) As Integer
The common sharing function Hour (TIMEVALUE for DATETIME) is used as an integer

Returns integer values from 0 to 23, representing hours of the day.

7

Public Shared Function Minute (TimeValue As DateTime) As Integer
The common sharing function Minute (TIMEVALUE for DATETIME) is used as an integer

Returns an integer value from 0 to 59, representing the minute of the hour.

8

Public Shared Function Month (DateValue As DateTime) As Integer
The public sharing function Month (DateValue will act as DATETIME) as an integer

Returns an integer value from 1 to 12, representing the month of the year.

9

Public Shared Function MonthName (Month As Integer, Abbreviate As Boolean) As String
The common sharing function MONTHNAME (month is an integer, referred to as Boolean) as a string

Returns a string value that contains the name of the specified month.

10

Public Shared Function Second (TimeValue As DateTime) As Integer
The common sharing function Second (TIMEVALUE for DATETIME) is used as an integer

Returns the second integer value from 0 to 59, which represents the minute.

11

Public Overridable Function ToString As String
The public can rewrite the ToString function as a string

Returns a string that represents the current object.

12

Public Shared Function Weekday (DateValue As DateTime, DayOfWeek As FirstDayOfWeek) As Integer
The common sharing function Weekday (DateValue will be used as a date time, week due to Firstdayofweek can) as an integer

Returns an integer value that contains a number that represents the day of the week.

13

Public Shared Function WeekdayName (Weekday As Integer, Abbreviate As Boolean, FirstDayOfWeekValue As FirstDayOfWeek) As String
The common sharing function WEEKDAYNAME (integer on weekdays, referred to as Boolean for short, FirstDayOfWeekValue as Firstdayofweek can) as a string

Returns a string value that contains the name of the specified workday.

14

Public Shared Function Year (DateValue As DateTime) As Integer
The common sharing function (DateValue is DATETIME for one year) as an integer

Returns an integer value that represents the year from 1 to 9999.


The above list is not exhaustive. F or a complete list of properties and methods for the DateAndTime class, see the Microsoft documentation.

The following program demonstrates some of these methods:

Module Module1
   Sub Main()
      Dim birthday As Date
      Dim bday As Integer
      Dim month As Integer
      Dim monthname As String
      ' Assign a date using standard short format.
      birthday = #7/27/1998#
      bday = Microsoft.VisualBasic.DateAndTime.Day(birthday)
      month = Microsoft.VisualBasic.DateAndTime.Month(birthday)
      monthname = Microsoft.VisualBasic.DateAndTime.MonthName(month)
      Console.WriteLine(birthday)
      Console.WriteLine(bday)
      Console.WriteLine(month)
      Console.WriteLine(monthname)
      Console.ReadKey()
   End Sub
End Module


When the above code is compiled and executed, it produces the following results:

7/27/1998 12:00:00 AM
27
7
July