Mark Voss

VBScript date & time functions

VBScript date & time functions

VBScript date and time functions can be used to return the system date and time in different formats for use on web pages. They can also be combined into useful sub procedures & functions for manipulating dates & times further.

In the last example, DateDiff simply returns the number of days between now and Christmas day this year so, if Christmas day has already passed, DateDiff will return a negative value.

We can fix this by checking if Christmas day has passed and, if it has, we add a year to the current year before doing the DateDiff:

Sub DaysToChristmas()

  'Has Christmas already passed this year?
  If Month(Now) > 12 Or (Month(Now) = 12 And Day(Now) > 25) Then
    'Use next year.
    UseYear = Year(Now) + 1
    UseYear = Year(Now)
  End If
  DaysUntil = DateDiff("d", Now, DateSerial(UseYear,12,25))

  Response.Write "The number of days until Christmas is: " & DaysUntil

End Sub

<p><% Call DaysToChristmas %></p>

The resulting output is:

Check back just after Christmas to see the difference in the output of the two versions!

Leave a Reply

Your email address will not be published. Required fields are marked *