The
elegant way
To
return the number of days through VBScript functions we need
to combine the use of three functions:
- DateSerial()
- DateAdd()
- Day()
Before
looking at the combination of these it's worth reviewing what
each of them can do.
1 DateSerial()
DateSerial()
can be used to turn elements of a date entity into a date,
for instance
intYear
=
2008
intMonth =
8
intDay =
28
response.write DateSerial(intYear, intMonth,
intDay)
produces
the output
28/08/2008
. Notice that the date format used in the output is determined
by the settings on the server since no explicit format is
specified for the date here.
An
important point here is that, this being month
, month number
8
, the following code returns the fist day of next month:
intYear
=
2008
intThisMonth =
8
intToday =
28
' Doesn't
matter
response.write DateSerial (intYear, intThisMonth
+ 1, 1)
The
output being
01/09/2008
. VBScript is clever enough to increment the year if we add
1 to month 12, as in
response.write
DateSerial(
2008
, 12 + 1, 1)
which
displays
01/01/2009
, next new year's day.
So
we now have a mechanism to determine the first days of the
given month and the month which follows it.
2 DateAdd()
This
function handles arithmetic on dates in a formal way. In this
current example we will use it to calculate the day before
the first day of next month: The last day of this month, that
is!
The
following line of code
Response.Write
DateAdd("d", -1, DateSerial(
2008
,
8
+ 1, 1 ))
gives
output of
31/08/2008
. It takes the date we calculated above,
01/09/2008
, and -- as we specify "d" for days and -1 to add
(take one away, that is) -- the function decrements the days
of the given date by one. Again, when days are manipulated,
months and years are updated as necessary.
We
now have a mechanism to determine the first and last days
of the given month. We could use a difference between the
two dates to return the number of days in the month. Since
the month always starts on the first (!) and we need an inclusive
count, using the Day()
function is an ideal way to get the count of days.
3 Day()
The
Day() function
return an integer which represents the day number in the specified
month, so
Day(
28/08/2008
)
returns
28
. Correct, since today is
28
.
August
.
and
Day(
01/08/2008
)
returns
1
.
More
importantly in this exercise:
Response.Write
"The number of days in the month is " & _
Day(DateAdd("d",
-1, DateSerial(Year(Now), Month(Now) + 1, 1)))
output
the string The number of days in this month is
31
. |