How to Subtract a Date in VB

How to Subtract a Date in VB thumbnail
Visual Basic makes it easy to manipulate dates.

Visual Basic, the simplest of the programming languages that comes with Microsoft's Visual Studio, accesses the sophisticated .NET libraries for many common functions, including date manipulation. For instance, subtracting dates to retrieve a span of time. It seems like a simple problem, but realistic details like leap years can foil a naive programmer.

Instructions

    • 1

      Create a new project by clicking "File" and "New Project." Name it "DateTutorial" and save it with all the settings left at their defaults.

    • 2

      Drag a button from the toolbox onto the design form. Double-click it to open the source-code editor.

    • 3

      Paste the following into the editor:

      <br /><br /><br /><br />? Dim d1 As Date = New Date("1999", "1", "30")<br /><br /> Dim d2 As Date = New Date("2010", "4", "23")<br /><br /><br /><br /> Dim span As TimeSpan = d2.Subtract(d1)<br /><br /> Debug.WriteLine(span.TotalDays)<br /><br /><br /><br />

      This defines two dates: January 30, 1999 and April 23, 2010. It then uses the "Subtract" method to find the difference between the two dates and prints it to the debugger panel in terms of the total number of days separating them.

Tips & Warnings

  • You can retrieve the TimeSpan in terms of TotalDays, TotalYears, TotalHours, TotalMinutes, or even TotalMilliseconds, depending on your needs.

Related Searches:

References

  • Photo Credit calendar with bow image by Photoeyes from Fotolia.com

Comments

You May Also Like

Related Ads

Featured