VBScript - Adding Days and Months to a Date


Alright, I usually like to blog about some IT related challenge that I've recently overcome but tonight I'm just going to post some relatively common code that I know at least one person according to my web site statistics seemed to be looking for today in my blog and must have come up empty handed so they had to go find it on any one of at least a thousand other sites about vbscript.

What where they looking for? The VBScript code to add 3 months to a date.

Here it goes...

VBScript has a built in function called "DateAdd" that specifically deals with adding or subtracting when dealing with a date/time variable.

To use it you will need to know the syntax and parameters that it needs to make the magic happen.

For my example I'm going to get the current date and time of the system by calling the "Now()" function which grabs the date and time from the PC the script is being run on.

To add one year, it goes like this.

DateAdd("m",3, Now())

Since I wrote this code in March it should return a numeric "6" for June.  To spell out the month you would have to due some more work and maybe I'll cover that in another post later.  The important thing to remember when working with dates and times using DateAdd, all your output will be numeric.

The vbscript function, DateAdd, needs a couple of items separated by commas to make it work.

WHAT IT NEEDS AND WHY

1. DateAdd needs to know the "Interval" parameter which is the part of the date your are wanting to work with.  In the sample above I used "m" to tell it that I want to add to the month. 

HINT: Don't forget to wrap interval parameter text in double quotes.

2. DateAdd needs the number you want to add to the date and in my sample I used "3". If you want to get a previous month then simply give DateAdd a negative number.

3. DateAdd needs to know what date you are working with. In my sample I used Now() to the current system date/time. You could have passed the date via a variable.

Where I had used "m" to add to the month, you only have to change to interval parameter to change the year, month, day, hour, minute or second.  Here is a list of all the interval parameters you can pass to the DateAdd function:

  • yyyy - Year
  • q - Quarter
  • m - Month
  • y - Day of year
  • d - Day
  • w - Weekday
  • ww - Week of year
  • h - Hour
  • n - Minute
  • s - Second

I know for some people the DateAdd function is like preschool but for people who are new to VBScript I know it helps a lot if someone stops to explain the how and why of how this stuff works.

Good luck and happy coding!
Rick

Comments

There have been no comments made on this article. Why not be the first and add your own comment using the form below.

Leave a comment

Commenting is restricted to registered users only. Please register or login now to submit a comment.