The DateDiff, DateAdd and DatePart VBScript Functions

The Datediff function

The Datediff function is a great way to calculate the interval period between two dates. If you set the interval parameter to m for months the function will return the amount of months between the two dates. The table below lists the interval periods you can set for the interval parameter.

Syntax: DateDiff(Interval,date1,date2)

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

<%
Response.write DateDiff("m","01/01/04",date) & " Months"
'date function returns todays date so its difference between 01/01/04 & today
%>

Output: 131 Months

The DateAdd function

The DateAdd() functions allows us to add or subtract from a date or time. DateAdd returns a date or time that has been modified by the number parameter.

Syntax: DateAdd(Interval, number, Date)

The interval argument accepts the following values:

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

<%
Response.write DateAdd("m",2,date)
'the date function returns today's date so we are adding 2 months on
'you can also substract i.e. -2
%>

Output: 20/02/2015
'this is UK format as the server is in the UK

<%
Response.write DateAdd("n",-25,time)
'the time function returns today's time so we are substracting 25 minutes
%>

Output: 12:28:40

The DatePart function

We can use the DatePart function to return the specified part of the date and time.

Syntax: DatePart(GetPartOftheDate, Date)

The GetPartoftheDate argument accepts the following values:

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

<%
Response.write "The Now function returns:" & Now & "<br>"
Response.write "Retrieve the year: " & DatePart("yyyy", Now)
%>

OutPut: The Now function returns:20/12/2014 12:53:40
Retrieve the year: 2014



Other date and time related tutorials:
Here's a code snippet to display the day and date (eg. Mon 25 December).
Here's a code snippet to display the day and date with the ordinal suffix (eg. Mon 25th December).
How to get the current month name
Display the dates and times
Time and Date based greetings
IsDate Function

LinksPro - Directory  and Link  Management Software

Get the best ASP hosting with DiscountASP.NET - great value, money back guarantee.

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Global ASP.NET Hosting Leader - Click Here