Tip Of the Month
http://www.ronshardwebapps.com

ASP Index

Other Tutorials: Ron's Hard Tutorials

January, 2003
Getting More Out of VBScript Date & Time Functions

The Topic:

In this month's tutorial, I discuss Date and Time functions with ASP and VBScript.  I'll go over many of the built-in VBScript Date/Time functions, and walk you through a custom function I created.  The function combines several built-in functions to enable you to display the current date and time on a webpage in virtually any format.

Who is this lesson for:


This VBScript and ASP tutorial is for beginners but not novices.  You should know or have...

  • The basics of ASP and VBScript development
  • How to call a Function()
  • The commands and syntax for displaying data on an ASP page with VBScript
  • The basic syntax for creating a Function
  • A general knowledge of the Date(), Time(), Now(), Left(), Right(), & Mid() functions
  • Knowledge of HTML basics

The Issue:

I needed to display the current date and time (and city) on the left navigation margin of every page on a website.  The margin was relatively narrow, about 110 pixels, and I needed to fit these date/time elements inside it: the full name of the day, the abbreviated month name, the day of the month, the year, and the time in AM/PM format without seconds.


Sunday
May. 18, 2008
6:37 AM

This is the format I needed.



When I began coding, I didn't think about the date/time requirement much, because I knew Visual Basic had the functions I needed to do this with no real effort.  I had forgotten about some of VBScript's shortcomings, and what I had brushed off as nothing was beginning to take too much thought (all of this took about 20 minutes, which is an eternity in the cyber world).

Why the Function was necessary:

I had planned to use the Now() function with a little re-work:


CodeResult
<%=Now()%>5/18/2008 6:37:35 AM



Now() returns both the date and time, but I would have to chop it to pieces with string functions and beat it with conversions to get it to work.  The main issue was using explicit breaks (carraige returns) to put the different elements on separate lines.  I couldn't trust web browsers to break up the date correctly, and returning the current time in AM/PM format without seconds wasn't as simple as I had first thought.  I decided working with the Now() function was not practical for this little thing, so I took a look at the FormatDateTime() function.

With the FormatDateTime() function, you can produce several different date formats, and the syntax is simple and easy to use.

FormatDateTime(Date[, NamedFormat])

where Date is any date or time, and NamedFormat is a VBScript constant.  You can use either the named format or the corresponding constant value, e.g. vbGeneralDate cooresponds to a value of 0, and they can be used interchangeably.


CodeResult
 FormatDateTime("Jan 1, 2002", vbGeneralDate) 1/1/2002
 FormatDateTime("Jan 1, 2002", 0)1/1/2002



The NamedFormat is optional.  If it is omitted, vbGeneralDate (the default) is assumed.  Using the NamedFormat is preferred over the constant value, because it makes code easier to understand.

The following tables summarize the FormatDateTime function with the Now(), Date(), and Time() functions (I needed to display the current date and time, so I would have to use one or a combination of these functions).



VBScriptFormatDateTimeFunction withNamedFormat and Now() Function
Constant Code Result
0  FormatDateTime(Now(), vbGeneralDate)  5/18/2008 6:37:35 AM
1  FormatDateTime(Now(), vbLongDate)  Sunday, May 18, 2008
2  FormatDateTime(Now(), vbShortDate)  5/18/2008
3  FormatDateTime(Now(), vbLongTime)  6:37:35 AM
4  FormatDateTime(Now(), vbShortTime)  06:37


VBScriptFormatDateTimeFunction withNamedFormat and Time() Function
Constant Code Result
0  FormatDateTime(Time(), vbGeneralDate)  6:37:35 AM
1  FormatDateTime(Time(), vbLongDate)  Saturday, December 30, 1899
2  FormatDateTime(Time(), vbShortDate)  12/30/1899
3  FormatDateTime(Time(), vbLongTime)  6:37:35 AM
4  FormatDateTime(Time(), vbShortTime)  06:37
Note the Dates returned by the Time() Function


VBScriptFormatDateTimeFunction withNamedFormat and Date() Function
Constant Code Result
0  FormatDateTime(Date(), vbGeneralDate)  5/18/2008
1  FormatDateTime(Date(), vbLongDate)  Sunday, May 18, 2008
2  FormatDateTime(Date(), vbShortDate)  5/18/2008
3  FormatDateTime(Date(), vbLongTime)  12:00:00 AM
4  FormatDateTime(Date(), vbShortTime)  00:00
Note the Time returned by the Date() Function




The issue with the FormatDateTime() function was similar to the issue with the Now() function.  I would still have to break up the date and time with string and conversion functions, and I couldn't use built-in VBScript functions like WeekDayName or MonthName on the values returned by FormatDateTime directly, so I concluded that I would need to create my own function.  Here is the function, which I will go over line-by-line in this tutorial.


Ron's Hard Date/Time Function for VBScript and ASP
<%

    Function rDateTime(rDate, rTime)

        DIM myDay, myDayName, myMonthName , myYear, myTime
        DIM myAMPM, myHour, myColon, myMinute

        'get AM or PM from the time
        myAMPM = Right(rTime,2)

        'get Hour and Minute
        myColon = instr(1, rTime, ":",vbBinaryCompare)

        IF myColon = 2 THEN
            myHour = Left(rTime,1)
            myMinute = Mid(rTime, 3, 2)
        ELSE
            myHour = Left(rTime,2)
            myMinute = Mid(rTime, 4, 2)
        END IF

        'concatenate the time
        myTime = myHour & ":" & myMinute & "&nbsp;" & myAMPM

        'get weekday number
        myDayName = weekday(rDate)

        'convert weekday number to weekday name
        myDayName = weekdayname(myDayName)

        'get the day, e.g. oct 19, 2002, will return 19
        myDay = Day(rDate)

        'get month number
        myMonthName = Month(rDate)

        'convert month number to month name (abbreviation True)
        myMonthName = MonthName(myMonthName, True)

        'get the year
        myYear = Year(rDate)

        'concatenate variables
        rDateTime = "<font class='time'>" & myDayName & "<br>" & _
            myMonthName & ".&nbsp;" & myDay & ",&nbsp;" & myYear & _
            "<br>" & myTime & "</font>"

    End Function

%>

The date and time are formatted in the last line of the function and there are infinite possibilities.


Code Result
<%=rDateTime(Date(),Time())%> Sunday
May. 18, 2008
6:37 AM



VBScript Date/Time Functions

I wanted to have each piece of the current date and time stored in a variable so I could manipulate and display the values as I pleased.  This function is not as long as it looks, it's about 19 lines, but only because I want to explain the code in detail.  First I'll give a quick and dirty explanation of the VBScript Date/Time functions.

Second() Function

As you might have guessed, this function returns the seconds from a given time.  I didn't need this function.  If I need seconds in the future, I'll get them with a string function.  The problem with using the function directly is it will return a one number value if seconds are less than 10.


CodeResult
<%=Second("4:20:05 PM")%>5


Noone displays the time like this: 4:20:5 PM, so using Second() for display purposes is not practical.  String functions would be more appropriate, and I use them in my function to store hour and minute in variables.


WeekDay() Function

The WeekDay() function returns a number representing the day of the week.  A value of 6 would represent Friday, assuming the systems First Day of the Week property is set to Sunday (1 would represent Sunday in that case).  I use WeekDay() along with WeekDayName() to store the name of the day in a variable.


CodeResult
   <%=WeekDay(Now())%>1
   <%=WeekDay(Date())%>1
   <%=WeekDay("January 1, 2003")%>4



WeekDayName() Function

The WeekDayName() function returns a string indicating the specified day of the week. This function only accepts a numeric value for Day of the Week, which is why I needed WeekDay() when I created my function.  The second parameter in WeekDayName() is an optional Boolean value that indicates whether or not the weekday name should be abbreviated.  The default is False, or not abbreviated.


CodeResult
   <%=WeekDayName(1)%>Sunday
   <%=WeekDayName(WeekDay(Date()))%>Sunday
   <%=WeekDayName(WeekDay(Date()), True)%>Sun



Notice how I combined the WeekDay() and WeekDayName() functions on one line.  I displayed them on separate lines for this tutorial, to make explaining the code for my function easier.


Day() Function

The Day() function returns a numeric value representing the day of the month.  As I explained, I wanted to store all parts of the date and time in a variable and this piece was no exception.


CodeResult
   <%=Day(Now())%>18
   <%=Day("January 15, 2003")%>15



Month() Function

The Month() function returns a number representing the month of the year.  I use this function to get the number of the month and then I use MonthName() to return the name of the month.  This is the same way I used WeekDay() and WeekDayName() together.


CodeResult
   <%=Month(Now())%>5
   <%=Month(Date())%>5
   <%=Month("January 1, 2003")%>1



MonthName() Function

The MonthName() function returns a string indicating the specified month of the year.  This function only accepts a numeric value for Month of the Year, and I use Month() to return the numeric value.  The second parameter in MonthName() is an optional Boolean value that indicates whether or not the month name should be abbreviated.  The default is False - not abbreviated.


CodeResult
   <%=MonthName(1)%>January
   <%=MonthName(Month(Date()))%>May
   <%=MonthName(Month(Date()), True)%>May



I combined the MonthName() and Month() functions in the examples above, but they are separated when we go through my function to make understanding each part simpler.


Year() Function

The Year() function returns the year (we are getting into the tough stuff now).


CodeResult
   <%=Year(Now())%>2008
   <%=Year(Date())%>2008
   <%=Year("January 2, 1997")%>1997



For a more detailed discussion of the functions listed above, go to Microsoft.com and see the VBScript Language Reference.

My Function

Here is an explanation of my function line by line...

First, there is the opening ASP script tag and then I use the Function keyword to define a function named rDateTime.  rDateTime takes two parameters: rDate and rTime.  Once the function is called from my ASP page (e.g. <%=rDateTime(Date(), Time())%>), rDate will hold the date returned by the Date() function, and rTime will hold the time returned by the Time() function.


<%

    Function rDateTime(rDate, rTime)



Next, I declare all of the variables I'll need for my function.  (I always use the Option Explicit statement in my ASP pages.  This forces me to declare all variables and makes debugging code much easier).


 DIM myDay, myDayName, myMonthName , myYear, myTime
 DIM myAMPM, myHour, myColon, myMinute



rTime holds a time with this format: 6:37:35 AM.  I want to store AM or PM in a variable named myAMPM.  I use the Right() string function to extract the last two characters from rTime.


myAMPM = Right(rTime,2)



I use the Instr() function to get the position of the first colon in rTime and store the value in a variable named myColon.  I use the variable to extract the Hour and Minute from rTime.


myColon = instr(1, rTime, ":",vbBinaryCompare)



myColon will be 2 if there is a one digit hour (e.g. 8:21:03 PM), or 3 if there is a two digit hour (e.g. 11:24:12 AM).  I use this fact in a decision structure, IF...Then...Else, to extract hour and minute from rTime.

If the colon is the 2nd character in the string, I use the Left() function to get the 1st character, which is the hour, and the Mid() function to get the 3rd and 4th characters, which is the minute.  If the colon is not the 2nd character, I use Left() to get the 1st and 2nd characters for hour, and Mid() to get the 4th and 5th characters for minute.  I store the values for hour and minute in variables named myHour and myMinute.


IF myColon = 2 THEN
    myHour = Left(rTime,1)
    myMinute = Mid(rTime, 3, 2)
ELSE
    myHour = Left(rTime,2)
    myMinute = Mid(rTime, 4, 2)
END IF



Now I can format the current time with hour, minute, and AM/PM without seconds included, and store it in a variable named myTime.


myTime = myHour & ":" & myMinute & "&nbsp;" & myAMPM
If Time() = 10:20:34 AM then the function would make: 
myTime = 10:20 AM



Next, I use WeekDay() to store a number that represents the day of the week in a variable named myDayName.  After I get a numeric value for the day, I use it with WeekDayName() to store the day name in myDayName.


'get numeric value for day of the week  
myDayName = WeekDay(rDate)

'convert numeric value to day name
myDayName = WeekDayName(myDayName)



I use the Day() function to get the numeric day of the month.


myDay = Day(rDate)



Now, I use Month() to store a number that represents the month of the year in a variable named myMonthName.  After I get a numeric value for the month, I use it with MonthName() to store the month name in myMonthName.


'get numeric value for month of the year  
myMonthName = Month(rDate)

'convert numeric value to abbreviated month name
myMonthName = MonthName(myMonthName, True)



I store the year in a variable named myYear.


myYear = Year(rDate)



Finally, I'm ready to format the current date and time and send it to my ASP page for display.  The last line of a function always consists of assigning the result of the function to the function name.


rDateTime = "<font class='time'>" & myDayName & "<br>" & _
            myMonthName & ".&nbsp;" & myDay & ",&nbsp;" & myYear & _  
            "<br>" & myTime & "</font>"



As you see, with all of the pieces stored in variables, formatting the current date and time turns into a simple concatenation exercise.


Code Result
<%=rDateTime(Date(),Time())%> Sunday
May. 18, 2008
6:37 AM



Whether you copy and paste my function or create your own function, you can display the current date and time in your ASP pages in any way, shape, or size, by combining the built-in VBScript Date/Time functions with a little brain power.





If you have any questions about January's tutorial, send me an email and I'll be happy to help.  See you in February!

-Ron

Other Tutorials: Ron's Hard Tutorials


Donations & Tips
Send Ron a Donation
Send Ron a DonationSend Ron a Donation
Send Ron a DonationSend Ron a Donation


[ Home | Top | Guest Book ]
ASP Index



Problems, Questions, FeedBack, Suggestions?
Please Email Ron

© 2002 Ron Williams
64.71.40.22