Software Development

Adding and subtracting date/time values in VB.NET

This tip shows how the <i>Date</i> object provides for simple manipulation, which allows you to add and subtract date/time values in VB.NET.

While it has become common practice for developers to manipulate VB.NET date/time values manually, it's never a good idea because the result is rarely a correct date/time value. Whenever you try to use your own calculation routines for adding and subtracting date/time values, you risk generating a bug since it's hard to check the code for all possible outcomes, whereas utilizing appropriate .NET objects and methods is sure to provide correct results.

As you can see in Listing A, the Date object provides for simple manipulation, which allows you to add and subtract date/time values in VB.NET. In the example, I define the Date variable dtNow and set it to the current date/time value. I utilize these Date object methods to manipulate the date: AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, and AddMilliseconds. For each method, I specify the number of years or months or hours to add. Subtraction is done by passing a negative value to the method. Notice that these methods will never result in an impossible date; manual manipulation cannot guarantee such results.

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!

5 comments
geraldchus
geraldchus

So, if the following is used 'Current TimeDate=#4/7/2012 7:00:00 PM# m_dteAddedAutoOff = TimeDate.AddHours(+5) Why would the m_dteAddedAutoOff =#4/8/2012# ? Your code doesnt take into account the time rolling over to a new day?

mody222
mody222

it is very difficult but after one month in front of my computer i did it and the results always right i am very sure egyptian computer programmer :d Email : mody_alex3@yahoo.com mail me to get the project

paper.bill
paper.bill

Much too glib. Date manipulation is a beastly task with many pitfalls. Try moving from the end of February to the end of March by adding one month? From the end of March back to the start of February - is it two months or one month and 28/31? It all becomes very relevant if we're working out your monthly salary :-)

Editor's Picks