Intro to VB.NET's DateTime

Level:
Level1

Often when working on an application we find ourselves needing to handle dates and times. Some common example uses of this are birthdates, appointment scheduling, expiration dates, timers, etc. Classic VB6 had some pretty good handling for Dates and Times, VB.NET takes it to a whole new level by giving us a good object oriented approach with the DateTime structure. In this tutorial we will get a good introduction to how we can handle dates and times in Visual Basic .NET.

Note: This tutorial has a corresponding source sample file: Date Time Source Examples


Here are a few of the DateTime highlights we will be covering in this tutorial:

  • When declareing a DateTime it is a struct not a class
  • A DateTime as the name implies holds both a date and time. If we want just one portion of it we can use the properties off of our DateTime instance.
  • DateTime’s are equitable and comparable

Note: If you already understand the basics of VB.NET’s DateTime structure you might want to jump over to the second part of this tutorial where we begin to learn more about the DateTime Functions Available in VB.NET.


A DateTime is a structure

DateTime is a structure not a class. A quick refresher on structures – they are declared with the Structure keyword in VB.NET. In fact the declaration for DateTime (deep inside one of Microsoft’s DLL’s) if it were in VB.NET would simply look like this:

Public Structure DateTime
…
End Structure

Since DateTime is a structure and not a class it is immutable and it is passed by value.

DateTime’s are immutable:

Immutable means that once you have a DateTime value you can’t change it without creating a new one. For example the following code would not compile:

Dim dateTime As DateTime = New DateTime(2011, 2, 20)
dateTime.Year = 20;

Because the dateTime.Year line is not valid since Year is a readonly property. If you are wondering how we would add years to a DateTime value than read on as we describe it below.

DateTime’s are passed by value:

Another consequence of the fact that DateTimes are structures is that they are passed around by value instead of by reference (which is how a Class instance is passed around). This can come back to bite you if you aren’t careful. Here is an example:

Private Sub btnStructs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
							Handles btnStructs.Click
	Dim dateTime As DateTime = New DateTime(2011, 2, 20)
 
	MessageBox.Show("Before method call: " & dateTime)  ' This will be 2/20/2011
	AddTwoMonthsMethod(dateTime)
	MessageBox.Show("After method call: " & dateTime) ' This will still be 2/20/2011
End Sub
 
Private Sub AddTwoMonthsMethod(ByVal dateTime As DateTime)
	dateTime = dateTime.AddMonths(2)
	MessageBox.Show("Inside method: " & dateTime.ToString())    ' This will be 4/20/2011
End Sub

In the example above you will notice that we create a DateTime called dateTime and set it to a specific date (2/20/2011). We then call our method called AddTwoMonthsMethod. This method simply adds TwoMonths to the specified dateTime argument and assigns it back. If DateTime were passed by reference this would work as expected but since it is passed by value our dateTime variable is not changed outside of the method.


DateTime stores both Date and Time (but we have access to the details)

As the name implies a DateTime variable stores both the date and time information. This can be confusing when for example we are working with someone’s birthdate. It’s pretty rare that we ask someone’s birthdate and want to also know the hour and minute that they were born. In cases like this we can always get just the Date portion of a DateTime using the Date property.

Dim dateTime As DateTime = New DateTime(2011, 2, 20, 3, 45, 33)
MessageBox.Show("Date and Time " + dateTime) ' Will be 2/20/2011 3:45:33 am
MessageBox.Show("Date Only " + dateTime.Date) ' Will be just 2/20/2011

As the comments indicate the first MessageBox call will show the full date and time: ‘2/20/2011 3:45:33 am’ where as the second call will show only the date portion ‘2/20/2011’. Besides the Date property DateTime variables have many other useful properties. Most of these are pretty intuitive for example: Day, Year, Month, Hour, Minute, etc. Along with this we have the TimeOfDay property that gives us a TimeSpan that matches the time portion of our DateTime variable. Two other interesting properties are DayOfWeek which returns 0 – 6 for Sunday through Saturday, and DayOfYear which will give us the day of the year from (1 – 365 or 1-366 for leap years).

Dim dateTime As DateTime = New DateTime(2011, 2, 20, 3, 45, 33)
MessageBox.Show("Date and Time " & dateTime) ' Will be 2/20/2011 3:45:33 am
MessageBox.Show("Date Only " & dateTime.Date) ' Will be just 2/20/2011
MessageBox.Show("TimeOfDay " & dateTime.TimeOfDay.ToString()) ' Will be 03:45:33 am
MessageBox.Show("Hour " & dateTime.Hour) ' Will be 3
MessageBox.Show("Day of Week " & dateTime.DayOfWeek) ' Will be 0 - for Sunday
MessageBox.Show("Day of Year " & dateTime.DayOfYear) ' Will be 51

DateTimes are Equatable and Comparible

The DateTime structure implements IEquatable<DateTime>. This interface defines one method, which interesting enough is Equals. This method takes one parameter of type DateTime. This parameter is the other DateTime to compare ourselves to. You can see this in action as follows:

Dim date1 As DateTime = New DateTime(2011, 2, 20)
Dim date2 As DateTime = New DateTime(2011, 2, 20)
Dim dateTime As DateTime = New DateTime(2011, 2, 20, 3, 45, 33)
MessageBox.Show(date1.Equals(date2).ToString()) ' Will be true
MessageBox.Show(date1.Equals(dateTime).ToString()) ' Will be false

Notice that our date1 is equal to our date2 because every part of them is the exact same. By the same token our date1 is not equal to dateTime because although the date portions are equal the time portions our not so they are in fact not equal.

Along with DateTime implementing the Equals method of the IEquatable interface, we can also make use of the actual equals and not equals operators (= and <>). This allows us to use the much more comfortable and more readable syntax as follows:

MessageBox.Show((date1 = date2).ToString()) ' Will be true
MessageBox.Show((date1 <> dateTime).ToString()) ' Will be true

The DateTime structure also implements IComparible. IComparible is very similar to IEquatable but the one method it defines is CompareTo. ComparteTo takes one parameter, which is the other thing we are comparing to. However, instead of returning a Boolean it returns an integer. This integer can represent one of three things:

  • If the return value is less than 0 then we are before the DateTime specified as a parameter
  • If the return value is greater than 0 then we are after the DateTime specified as a parameter
  • If the return value is 0 then we are equal to the DateTime specified as a parameter

Below is some example code that demonstrates these three scenarios:

Dim date1 As DateTime = New DateTime(2011, 2, 20)
Dim date2 As DateTime = New DateTime(2011, 2, 25)
Dim date3 As DateTime = New DateTime(2011, 2, 20)
MessageBox.Show(date1.CompareTo(date2).ToString()) ' Will be -1
MessageBox.Show(date2.CompareTo(date1).ToString()) ' Will be 1
MessageBox.Show(date1.CompareTo(date3).ToString()) ' Will be 0

Similar to the equals handling we are also able to use the more common (and more understandable) operators >, >=, <, <= to do our comparisons. Here is what some of those look like:

MessageBox.Show((date1 < date2).ToString()) ' Will be true
MessageBox.Show((date1 > date2).ToString()) ' Will be false
MessageBox.Show((date1 >= date3).ToString()) ' Will be true


Summary

Almost every real world application makes use of dates and times in some form or fashion. Fortunately for us VB.NET developers we have a rich DateTime data structure provided for us by Microsoft. Using the .NET DateTime we are able to handle just about any situation life may throw at us from simple stop watch type applications to complex scheduling programs VB.NET makes it easy for us to crank out the code we need to provide a rich user experience.

Now that you’ve got a good solid understanding of the DateTime structure, feel free to visit the follow up tutorial to this one where you can learn more about the .NET DateTime Functions.


Note: This tutorial has a corresponding source sample file: Date Time Source Examples

If you enjoyed this post, subscribe for updates (it's free)

This can further be

This can further be elaborated in a different way to make sure things are done in a proper format at VB.NET.