Determine the number of days between dates in VB.NET
Takeaway: Trying to figure out how many days there are between two given dates? Find out why you may want to use VB.NET's TimeSpan object.
Developers often deal with various date manipulations in applications. If you need a simple way to figure out how many days there are between two given dates, consider using VB.NET's TimeSpan object.
Listing A shows how you can use the TimeSpan object to obtain the elapsed amount of time between two dates. Then you will use the Subtract method to find the actual number of days between the two dates.
Notes about the example
I set a start date with a Date variable, dtStartDate, and set its value to January 1, 2007. I also declared other variables I will use, including: tsTimeSpan as a TimeSpan object, iNumberOfDays as an Integer, and strMsgText as a String. I set the value of the tsTimeSpan variable to the difference between current date/time and the value of dtStartDate.
In order to calculate the number of days between current date/time (Now) and the dtStartDate, I use the TimeSpan object's Days property and set its value to iNumberOfDays. Then I create a text that I will show in a message box by concatenating necessary text and variables in setting the value for strMsgText. The last step is displaying the value of strMsgText in a Message box.
Miss a tip?
Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!
Print/View all Posts Comments on this article
SponsoredWhite Papers, Webcasts, and Downloads
- Number Systems Decoded - Binary, Decimal, and Hexadecimal Global Knowledge
- TCP/IP Troubleshooting Global Knowledge
- Bust a Move with Your SSIS - Passing Package Variables Global Knowledge
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET


