On MovieTome: Did INDY 4 "Nuke the Fridge"?

Determine the number of days between dates in VB.NET

Tags: Microsoft development tools, Programming languages, .NET, Irina Medvinskaya, TimeSpan object, TimeSpan, strMsgText, dtStartDate, Microsoft Visual Basic.Net, Visual Basic Tips Newsletter

  • Save
  • Print
  • Digg This
  • 1

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!

  • Save
  • Print
  • Digg This
  • 1

Print/View all Posts Comments on this article

Problem with timespanmoira@...  | 03/23/07
Code works on VS 2003irina_medvinskaya@...  | 03/23/07
Problem with timespan...solutionlsweeke@...  | 03/23/07
No luck :(moira@...  | 03/26/07
And in VB6 do it this way...ChuckSomerville  | 03/23/07
Thanks Chuckjoemach  | 04/13/07
RE: Determine the number of days between dates in VB.NETgretchen@...  | 01/04/08

What do you think?


advertisement
Click Here