Response.Redirect in Classic ASP

Response Object and HTML Encoding

The response object is often used in conjunction with various kinds of coding schemes. No discussion of response would be complete without a discussion of how to “handle” or “escape” special characters. This sample script demonstrates common conversion and transformation commands that make sense to use with the response.write command:

<html><head>
<title>Response object</title>
</head><body bgcolor="#FFFFFF">
<%
' The response object can be used to write text
' but sometimes some functions must be used to transform
' the text instead of sending as is to the browser

response.write "<B>Hyperion</b> by <I>Dan Simmons</i> is a great novel"
response.write "<p>"
response.write server.htmlencode("<B>Hyperion</b> by <I>Dan Simmons</i> is a great novel")
response.write "<p>"

response.write "Joe Smith & Hilda = a team"
response.write "<p>"
response.write server.URLencode("Joe Smith & Hilda = a team")
%>

</body></html>

Response Object – Redirects

The response object can be used to decide what page to send a user to next. Specifically the response.redirect method will work in that capacity. We have made a script formjump.asp that takes advantage of this.

<html><head>
<TITLE>FormJump.asp</TITLE>
</head><body bgcolor="#FFFFFF">
<form action="FormJumpRespond.asp" method="get">
<SELECT NAME="wheretogo">
<OPTION SELECTED VALUE="fun">Fun</OPTION>
<OPTION value="news">Daily News</OPTION>
<OPTION value="docs">ASP IIS3 Roadmap/Docs</OPTION>
<OPTION value="main">MainPage of ActiveServerPages.com</OPTION>
<OPTION value="sample">IIS 3 Sample ASP scripts</OPTION>
</SELECT>
<input type=submit value="Choose Destination">
</form>
</body></html>
The responder that reacts to this form is:

<%response.buffer=true%>
<html><head>
<title>formjumprespond.asp</title>&
<body bgcolor="#FFFFFF">
<%
' My ASP program that redirects to URL
thisURL="http://www.activeserverpages.com"
where=Request.QueryString("Wheretogo")
Select Case where
case "main"
response.redirect thisURL & "/"
case "samples"
response.redirect thisURL & "/aspsamp/samples/samples.htm"
case "docs"
response.redirect thisURL & "/iasdocs/aspdocs/roadmap.asp"
case "news"
response.redirect "http://www.cnn.com"
case "fun"
response.redirect "http://www.dilbert.com"
End Select
response.write "All dressed up and I don't know where to go<br>"
response.write "I recommend --> " & "<br>"
response.write server.htmlencode(thisURL & "/learn/test/res2.asp?where=fun") & "<br>"
response.write "for a good laugh!" & "<P>"
%>
</body></html>

Do..While..Loops in ASP

Do Loop Part #1  by Charles Carroll

To execute a code sequence more than once ASP provides:
* DO, LOOP
* WHILE, WEND
Either of these statements can be followed by UNTIL or WHILE.

DO UNTIL
…..code to be repeated…
LOOP

DO
…..code to be repeated…
LOOP UNTIL

Do Loop and Timeouts by Charles Carroll

A loop that is infinite will not run forever. IIS will timeout the script (default is 90 seconds).

Here is an infinite loop that IIS will timeout:

<%response.buffer=true%>
<TITLE>doloop1.asp</TITLE>
<body bgcolor="#FFFFFF">
<HTML>
<%
DO
counter=counter+1
response.write counter & "<br>"
response.flush
LOOP
%>
</BODY>
</HTML>

Here is an infinite loop that we explicitly set a timeout for:

<%
response.buffer=true
server.scripttimeout=20
%>
<TITLE>loop2.asp</TITLE>
<body bgcolor="#FFFFFF">
<HTML>
<%
DO
counter=counter+1
response.write counter & "<br>"
response.flush
LOOP
%>
</BODY>
</HTML>

It has been assumed that a timed out script was impossible to intercept, but the next lesson shows how to use the transactional aspect of an ASP script to capture this elusive condition.

Do Loop Intercept Timeouts by Charles Carroll

The transactional nature of ASP pages can be used to intercept a script timeout.
loop3.asp traps a timeout:

<%@ TRANSACTION=Required%>
<%
response.buffer=true
server.scripttimeout=20
%>
<HTML>
<TITLE>loop3.asp</TITLE>
<body bgcolor="#FFFFFF">
</BODY>
<%
DO
counter=counter+1
response.write counter & "<br>"
LOOP
response.flush
response.write "Script executed without incident"
%>
</HTML>
<%
Sub OnTransactionAbort()
response.clear
Response.Write "The Script Timed Out"
end sub
%>

loop4.asp succeeds and does not trigger the trap:

<%@ TRANSACTION=Required%>
<%
response.buffer=true
server.scripttimeout=40
%>
<HTML>
<TITLE>loop4.asp</TITLE>
<body bgcolor="#FFFFFF">
</BODY>
<%
DO  UNTIL counter=400
counter=counter+1
response.write counter & "<br>"
LOOP
response.flush
response.write "Script Exexuted without incident!"
%>
</HTML>
<%
Sub OnTransactionAbort()
response.clear
Response.Write "The Script Timed Out"
end sub
%>

Digital Certificates & Encryption

This is a white paper dedicated to Digital Certificates & Encryption, how they work and apply to Internet Commerce

The Need for Security
On the Internet, information  you send from one computer to another passes through numerous systems before it reaches its destination. Normally, the users of these intermediary systems don’t monitor the Internet traffic routed through them, but someone who’s determined can intercept and eavesdrop on your private conversations or credit card exchanges. Worse still, they might replace your information with their own and send it back on its way.

Due to the architecture of the Internet and intranets, there will always be ways for unscrupulous people to intercept and replace data in transit. Without security precautions, users can be compromised when sending information over the Internet or an intranet. This has serious implications for Internet Commerce. For Internet Commerce to exist, there has to be a means to secure data sent over the Internet. Without a secure means of communication, commerce cannot exist.

How do I protect my data?

Encryption & Digital Certificates are the solution for Internet Commerce. Used together, they protect your data as it travels over the Internet.
Encryption is the process of using a mathematical algorithm to transform information into a format that can’t be read (this format is called cipher text). Decryption is the process of using another algorithm to transform encrypted information back into a readable format (this format is called plain text).
Digital Certificates are your digital passport, an Internet ID. They are verification of you who you are and the integrity of your data.

Combined, encryption and digital certificates protect and secure your data in the following four ways:.
* Authentication: This is digital verification of who you are, much in the same way your driver’s license proves your identity. It is very easy to send spoofed email. I can email anyone in the world pretending I am the President of the United States. Using standard email, there is no way to verify who the sender is, i.e. if it is actually the President. With digital signatures and certificates, you digitally encode verifiable proof of your identity into the email.
* Integrity: This is the verification that the data you sent has not been altered. When email or other data travels across the Internet, it routes through various gateways (way stations). It is possible for people to capture, alter, then resend the message. Example, your boss emails the company president stating that you should be fired. It is possible for you to intercept that email and change it saying you deserve a $10,000 raise. With digital certificates, your email cannot be altered without the recipient knowing.
* Encryption: This ensures that your data was unable to be read or utilized by any party while in transit. Your message is encrypted into incomprehensible gibberish before it leaves your computer. It maintains it encrypted (gibberish) state during it’s travel through the Internet. It is not de-crypt until the recipient receives it. Because of the public-key cryptography used (discussed later) only the recipient can decipher the received message, no one else can.
* Token verification: Digital tokens replace your password which can be easily guessed. Tokens offer a more secure way of access to sensitive data. The most common way to secure data or a web site is with passwords. Before anyone access the data, they are prompted with their user login id and password. However, this is easily cracked using various security software (such as Crack 5.0, etc.). Also, passwords can be found with other means, such as social engineering. Passwords are not secure. Token verification is more secure. Your digital certificate is an encrypted file that sits on your hardrive. When you need access to a system, that systems asks you for your digital certificate instead of a password. Your computer would then send the certificate, in encrypted format, through the Internet, authorizing you for access. For this to be compromised, someone would have to copy this file from your computer, AND know your password to de-crypt the file.
How does it all work?

Encryption

To understand how this all works, we need to start with the basics. Encryption has been around for centuries, Julius Caesar used encrypted notes to communicate with Rome thousands of years ago. This traditional cryptography is based on the sender and receiver of a message knowing and using the same secret key: the sender uses the secret key to encrypt the message, and the receiver uses the same secret key to decrypt the message. For Caesar, the letter A was represented by the letter D, B by the letter E, C by the letter F, etc. The recipient would know about this sequence, or key, and decrypt his message. This method is known as secret-key or symmetric cryptography. Its main problem is getting the sender and receiver to agree on the key without anyone else finding out. Both sides must find some “secure” way to agree or exchange this common key. Because all keys must remain secret, secret-key cryptography often has difficulty providing secure key management, especially in open systems with a large numbers of users, such as the Internet.
21 years ago, a revolution happened in cryptography that changed all this, public-key cryptography. In 1976, Whitfield Diffie and Martin Hellman, introduced this new method of encryption and key management. A public-key cryptosystem is a cryptographic system that uses a pair of unique keys (a public key and a private key). Each individual is assigned a pair of these keys to encrypt and decrypt information. A message encrypted by one of these keys can only be decrypted by the other key in the pair:
* The public key is available to others for use when encrypting information that will be sent to an individual. For example, people can use a person’s public key to encrypt information they want to send to that person. Similarly, people can use the user’s public key to decrypt information sent by that person.
* The private key is accessible only to the individual. The individual can use the private key to decrypt any messages encrypted with the public key. Similarly, the individual can use the private key to encrypt messages, so that the messages can only be decrypted with the corresponding public key.

What does this mean?

Exchanging keys is no longer a security concern. I have my public key and private key. I send my public key to anyone on the Internet. With that public key, they encrypt their email. Since the email was encrypted with my public key, ONLY I can decrypt that email with my private key, no one else can. If I want to encrypt my email to anyone else on the Internet, I need their public key. Each individual involved needs their own public/private key combination.

Now, the big question is, when you initially receive someone’s public key for the first time, how do you know it is them? If spoofing someone’s identity is so easy, how do you knowingly exchange public keys, how do you TRUST the user is really who he says he is? You use your digital certificate. A digital certificate is a digital document that vouches for the identity and key ownership of an individual, a computer system (or a specific server running on that system), or an organization. For example, a user’s certificate verifies that the user owns a particular public key. Certificates are issued by certificate authorities, or CAs. These authorities are responsible for verifying the identity and key ownership of the individual before issuing the certificate, such as Verisign.

Authentication & Integrity

We now have a secure means of encrypting data, one of the four methods of securing data on the Internet. Two others, authentication and data integrity, are combined in what is called a digital signature. A digital signature works as follows:
* Authentication: a specific individual sent a message (in other words, no impersonator claiming to be the individual sent the message).
* Integrity: this particular message was sent by the individual (in other words, no one altered the message before it was received).
When you email someone, your public/private key combination creates the digital signature. It does this using the following format:
1. The sender uses a message-digest algorithm to generate a shorter version of the message that can be encrypted. This shorter version is called a message digest. Message digests and message-digest algorithms are explained in the next section.
2. The sender uses their private key to encrypt the message digest.
3. The sender transmits the message and the encrypted message digest to the recipient.
4. Upon receiving the message, the recipient decrypts the message digest.
5. The recipient uses the hash function on the message to generate the message digest.
6. The recipient compares the decrypted message digest against the newly generated message digest.
* If the message digests are identical, the recipient knows that the message was indeed sent by the person claiming to be the sender and that the message was not modified during transmission.
* If the message digests differ, the recipient knows that either the message was sent by someone else claiming to be the sender or that the message was modified or damaged during transmission.
The encrypted message digest serves as a digital signature for the message. The signature verifies the identity of the sender and the contents of the message.

If the message is sent by someone claiming to be the sender, this person does not have access to the sender’s private key. The person claiming to be the sender must use a different private key to encrypt the message digest.

Because the recipient uses the sender’s public key to decrypt the message digest (and not the actual public key corresponding to the private key used to encrypt the message digest), the decrypted message digest will not match the newly generated message digest.
If the message was modified during transmission, the hash function will generate a different message digest when applied after the transmission.

Tokens

Tokens represent the fourth security option by replacing passwords. Tokens are simply your digital certificate residing on your hardrive. When a computer prompts you for your password,  your computer sends your certificate over the Internet instead. Your certificate verifies your identity instead of the password. This is a more secure (and easier) means of verification.

How Secure is all This?

Just how secure is encryption. The strength of encryption is measured in bits, or how big the key is. The bigger the key, the stronger the encryption. There are currently 3 commonly used key sizes used commercially, 40, 56, and 128 bit. Originally, the government allowed only 40 bit keys for exportation. However, this proved far to weak for security. In February of 1997, a college student was able to crack 40 bit encrypted data within 4  hours .
Berkeley — It took UC Berkeley graduate student Ian Goldberg only three and a half hours to crack the most secure level of encryption that the federal government allows U.S. companies to export.

Yesterday (1/28) RSA Data Security Inc. challenged the world to decipher a message encrypted with its RC5 symmetric stream cipher, using a 40-bit key, the longest keysize allowed for export. RSA offered a $1,000 reward, designed to stimulate research and practical experience with the security of today’s codes.

Goldberg succeeded a mere 3 1/2 hours after the contest began, which provides very strong evidence that 40-bit ciphers are totally unsuitable for practical security.

In June of 1997, a organized group of people were able to crack 56 bit DES encryption in 140 days. This group shared their resources throughout the Internet utilizing software called DESCHALL. With a possible 72 quadrillion keys to test, this distributed attack would require an incredibly large amount of computing power. And compute the DESCHALL team did, at some points testing almost seven billion keys per second.

In the end, the DESCHALL effort solved the DES challenge after only searching 24.6% of the key space. (about 18 quadrillion keys!) The winning key was determined by Michael Sanders, using a Pentium 90 MHz desktop PC with 16 megs of RAM.

Many believe this security is good enough. By the time your data can be compromised, (3 months) it is of little value because it took so long.  However, to truly ensure the security of your data, most Internet Commerce uses 128 bit encryption. Keep in mind, key strength increases exponentially, making 128 bit encryption thousands of times more difficult to compromise. Because of its strength, the government has prohibited its exportation, it can only be used within the United States. At this time, no one has cracked this encryption. 128 bit encryption is expected to remain secure well past the year 2000.

What it Looks Like

Below is an example of a message that has been encrypted and signed, but intercepted before the recipient has received it.   Notice how the body of the entire message is “gibberish”, i.e., the message cannot be read.  That is what encryption looks like.

Below is an example of the same message, but received by the intended recipient.  The recipient has decrypted the message and verified the message’s integrity & /authenticity.  The protocol or Internet standard used for Digital Certificates is X.509 & S/MIME.  Any email system that has these open based standards can use Digital Certifcates for Internet Commerce.  The image below is of Netscape  Navigator, which is both X.509 and S/MIME compliant.

Conclusion

Utilizing digital certificates and encryption, users can easily and securely communicate on the Internet. This combination of ease of use and security lays the foundation for commerce. As users gain confidence and experience using these tools, Internet Commerce, much like encryption, will grow exponentially.

Cookies?

Have you noticed how all those websites on the net are getting “smarter” all of a sudden? You know, like the way message boards remember your nickname, some sites remember your password so you won’t have to retype it every time, electronic malls remember what you last put in your virtual shopping cart etc’.
This is all because of cookies. Cookies are small files which a website can request your browser to create and then retrieve information from them. Websites can put your password or any other information in these files.
If you don’t want your co-workers or other people to sniff around and see where you’ve been visiting, what items you’ve been buying etc’, you should delete them when you don’t need them.
On Unix, your cookies would usually be stored somewhere in your home directory (usually /home/your-login, /usr/your-login or /usr/local/your-login if you’re a regular user and /root if you’re root, but anyone with write access to /etc/passwd can change that).
On Windows and Mac, cookies are stored on a sub-directory at your browser’s directory called cookies.

Note 1: you can tell your browser to ask you before accepting a cookie. Just play around with it’s preferences menu, you’ll find it (there are so many browsers out there so I can’t give a detailed explanation for every single one).
Note 2: if you’re browsing from a public computer, do not save any cookies, or other people will be able to snoop around and look at your cookies or even enter various websites with your passwords, your credit card number etc’.

A reader called Stone Cold Lyin Skunk has pointed out to me that the cookies.txt file may be found in the netscapeusersdefault directory. This happens when you register your user (Netscape let’s you have multiple users for the same program, each user with his own settings etc’) without giving it a username.
He also pointed out to me that some websites will require you to accept cookies in order to enter them.
Also, he recommended to beware of your browser’s history file (information on removing it can be found on the “Where Can I Learn More About Anonymity?” chapter), as well as your cache and your preferences.js files, because they may reveal your browsing habits (where have you been, etc’).

.chk files?

Stone Cold Lyin Skunk has pointed out that if you’re running Windows and you do a quick reboot (hold down shift while telling Windows to reset) Windows generates a file called FILE0001.chk, FILE0002.chk etc’ (usually found on c:). You will be amazed to see how much information you could find in these files! Delete them ASAP!

Anonymous Remailers?

Previously I have demonstrated to you what a person with very little knowledge can find out about you just by knowing your Email address. Now it is obvious that to keep your privacy, you need to sign up for a free Email account (such as Hotmail [hotmail.com], Yahoo mail [mail.yahoo.com], ZDNet Mail [zdnetmail.com], Net @ddress [netaddress.com], Bigfoot [bigfoot.com] etc’). But what if you had a special Email address on a free server that automatically forwards all incoming Email to your real mailbox and keeps all the information discreet?
These are called Anonymous Remailers. Most of them are free and live out of contributions and/or sponsor banners they place on their website.
You can find many many Anonymous Remailers at http://www.theargon.com.

Here’s a good example for an Anonymous Remailer:
First, head to http://anon.isp.ee (by the way, the extension .ee stands for Estonia) and sign up your free account. Once you’re a registered user, send an Email to robot@anon.isp.ee with no subject and the following content:
user: your username
pass: your password
realaddr: your recipient’s Email address.
realsubj: the subject of your mail.
Example: if I want to send an anonymous mail containing the following:

Subject: ANONYMITY RULEZ!!
Hi.
This is an anonymous Email message.
Let’s see you trace me now!

to bgates@microsoft.com, and your username is user and your pass is pass, send the following Email to robot@anon.isp.ee (remember not to enter a subject):

user: user
pass: pass
realaddr: bgates@microsoft.com
realsubj: ANONYMITY RULEZ!!
Hi.
This is an anonymous Email message.
Let’s see you trace me now!

You’ll receive an Email notification from anon.isp.ee once your message has been delivered. Once your recipient will reply to this Email, the message will return to you.

You can also use web-based anonymous remailers such as Replay Associates , but it won’t let you receive replies.

Encryption?

Everyone can read your Email. Whether it’s some script kiddie who hacked your Hotmail account, a skilled cracker (or a script kiddie with a lot of free time) that hacked your POP3 mailbox or a person who got your Email by mistake. If you don’t want other people to read your Email, use PGP.
Everyone who uses PGP can have their own PGP key. A key consists of tons of characters, whether they are lowercase or uppercase letters, number or symbols. After you make your key, you need to transfer it to everyone you want to send encrypted mail to. Once they have it, you can start sending encrypted mail to them and they’ll be able to use your key to decrypt it.
Note: PGP is very strong and can only be broken with giant supercomputers. The longer your key is, the harder it is to break the encryption.

Proxies

Proxies were first invented in order to speed up Internet connections. Here’s how they work:
You are trying to connect to a server on the other side of the planet. Your HTTP requests are sent to your proxy server, which is located at your ISP’s headquarters, which are a lot closer to you than that far-away server. The proxy first checks if one of it’s users has accessed this website lately. If so, it should have a copy of it somewhere on it’s servers. Then the proxy server starts the connection only to check if his version is not outdated, which only requires him to look at the file size. If it has the latest version, it will send the file to you, instead of having the far server send it to you, thus speeding up the connection. If not, it will download the requested files by itself and then send them to you.
But proxies can also be used to anonymize yourself while surfing the web, because they handle all the HTTP requests for you.
Most chances are that your ISP has a proxy. Call tech support and ask them about it. But the problems with proxy access given to you by your ISP is:
1. Some ISPs don’t even have proxies.
2. The website owner would still be able to know what ISP you are using and where do you live, since this kind of proxies are not public and they can only be accessed by users of that ISP. For such cases, there is a solution – public proxies.
You can find a list of public proxies everywhere. Here are two good URLs to start from:

1. http://www.theargon.com
2. http://www.cyberarmy.com/lists

To configure your web browser to use a proxy server, find the appropriate dialog box in your settings dialog box (it varies from different browsers).

Note: some proxy servers will also handle FTP sessions (some might handle FTP only).

Wingates?
Wingate is a program that is used to turn a PC running Windows 9x or NT into a proxy server. Here are several reasons for why a person would want to run such an application and turn his computer into a proxy:

1. If he owns an ISP and he wants to set up a proxy for it.
2. If he wants to turn his computer into a public proxy.
3. If he wants to give Internet access to a whole bunch of computers that are connected by a Local Area Network, but he can provide Internet access for only one computer. In that case, he would turn his computer into a proxy server and set all the other computers on the network to use him as a proxy. That way all the rest of the computers on the network will relay their HTTP and FTP requests through a single computer, a single modem and a single Internet account.

The problem with Wingates is that they’re highly… well… they’re very… how should I say this? Stupid. Just plain stupid. Why is that?
EVERYONE can connect to your little proxy by simply connecting to port 1080 on your computer and typing ‘target-ip-address-or-hostname port’ (no quotes) and replace target-ip-address-or-hostname with the IP address or the hostname they want to connect to, and replace port with the destination port. The “wingated” mahcine will then relay your input through it, but it will seem like the wingated machine is connecting to the target computer, not you.
Sure, the sysadmin of the wingated machine can change that port to a different one, but this is the default, and if you’re stupid enough to use Wingate you probably won’t want to play with the defaults.
First of all, if you need to use Wingate for some reason, use SyGate instead. It does exactly what Wingate does, only it won’t serve EVERYONE like Wingate does.
Now, these Wingates can be used to anonymize practically anything. Also, every program that can be set to run behind a SOCKS firewall (most IRC clients, most instant messangers and most web browsers) will automatically do the dirty work of routing your stuff through it if you’ll give them the IP/hostname and the appropriate port for the wingated machine.
Wingates can also be used to get into IRC channels you got banned from (by faking your IP).

WARNING: some IRC networks run bots that will kick out people using Wingates. These bots try to connect to random people on port 1080. If they succeed, they kick you out. This works because the IRC network, as well as everyone on it, thinks that your IP is the wingated machine’s IP. If the bot tries to connect to your IP on port 1080, it will actually go to the wingated machine. The bot will then detect that your IP is actually a wingate and kick you off (since it’s being run by the IRC network and given enough priviledges to kick out anyone).

You can find lists of Wingates at http://www.cyberarmy.com/lists. There are also tons of Wingate scanners out there that can scan whole subnets and look for Wingates, but this might take some time (and make your ISP get suspicious), so you’d just better go for CyberArmy’s lists.

Working with Date and Time in ASP

Summary

Including the date and/or time on a web page can be a subtle yet valuable addition when designing a web site. The addition of the date to the home page can create the impression that a site is constantly being updated with new content since each time a visitor loads the page, the current date will be displayed.

In this tutorial I’ll teach you how to add the date and time to your ASP pages using the VBScript FormatDateTime() function. I’ll explain how the function works, teach you how to integrate it into your ASP pages and illustrate the output you’ll get depending on the arguments you pass. I’ll round out the tutorial of the FormatDateTime() function by covering a few limitations that it has, which might or might not be a big deal depending on your specific needs.

Just FYI, this article assumes you know basic HTML and how to add ASP scripts to your web pages.

The FormatDateTime() Function

Microsoft provides a ton of predefined VBScript functions designed to reduce coding time. The FormatDateTime() function is one of those powerful functions and is really easy to use, too. This function uses the following format:

FormatDateTime(date, format)

There are two arguments the function accepts: date and format. Table 1-1 below describes these arguments in greater detail:

Table 1-1: The FormatDateTime() function and its arguments

Argument Argument Description
date This argument is required and can be any valid date expression such as Date or Now

format This format constant or format value specifies how the date and/or time will be displayed on your ASP page.

When specifying the format argument, you can either type the Visual Basic constant name (name in left column), or the constant’s corresponding value (0 – 4, from the middle column). They do the same thing, it’s just less typing if you use the value.

Constant
Format Value
Format Description
vbGeneralDate
0
This is the default. Not specifying a value or specifying 0 will produce a date in the format of mm/dd/yy.

If the date expression is Now, it will also return the time, after the date, in hh:mm:ss PM/AM format.

vbLongDate
1
This is my personal favorite 🙂 Passing this value will produce a date in the format of
weekday, month day, year*

* The year is Y2K compliant :-).

vbShortDate
2
Passing this value returns a date formatted just like the default of 0 (mm/dd/yy).
vbLongTime
3
Passing this value returns the time in hh:mm:ss PM/AM format.

vbShortTime
4
Passing this value returns military time in this format hh:mm

Table 1-1 is a good reference once you’ve got a feel for how the FormatDateTime() function works or if you’re an experienced programmer. For those of you that aren’t clear on how all the information in table 1-1 relates to “real world” implementations, let’s take a look at some examples:

Returning the Current Date

If you would like to display the current date, here are a few different ways to do it along with the results they produce:

<%= FormatDateTime(Date) %> returns: 7/14/2012
(You would get the same result by coding this: <%=FormatDateTime(Date, 0) %>)

<%= FormatDateTime(Date, 1) %> returns: Friday, July 14, 2012

<%= FormatDateTime(Date, 2)%> returns: 7/14/2012

Returning the Current Time

If you would like to return the current time, here are a couple of ways to do that:

<%= FormatDateTime(Now, 3)%> returns: 6:42:31 AM

<%= FormatDateTime(Now, 4)%> returns: 06:42

Returning the Current Date and Time

If you would like to return the current date and time together, here’s how to do just that:

<%= FormatDateTime(Now) %> returns: 7/14/2012 6:42:31 AM

If you’re like me, you probably don’t like the way the date and time displays above; it’s not very cool looking, is it? In cases like this, you can actually include two FormatDateTime() functions next to each other, in order to get the date and time in a more desriptive format, like this:

<%= FormatDateTime(Date, 1) %>&nbsp;&nbsp;<%= FormatDateTime(Now, 3)%> returns:
Friday, July 14, 2012 6:42:31 AM

Adding the code to your page

Integrating the code into your ASP pages is really easy; here is how the code would look on a page with basic HTML to display the date:

<html>
<head>
<title>Here’s the date</title>
</head>

<body>

Thank you for coming to this page. The current date is: <%= FormatDateTime(Date, 1) %>

</body>

</html>

Limitations of the FormatDateTime() function

The FormatDateTime() function is an extremely handy bit of code that can help you add a touch of flair almost instantly. I would like to mention four limitations that stick out in my mind, which may be an issue to you (or your clients) depending on the project at hand:

Limitation 1: The unneeded zero

On the first through ninth days of a month the day shows up in the format of “Month 01, Year”. I know it seems like a small thing but trust me, it’s can be a big deal to some.

Limitation 2: Only basic formatting allowed

You are limited to basic formatting of the string that’s returned by the FormatDateTime() function. Since the date and/or time function returns is a single string, you can bold, italicize and change the whole date/time by adding HTML or style sheet tags around it, but you can’t change the display properties for a single part (e.g., the month).

With the FormatDateTime() function, you can do this:

<b><%= FormatDateTime(Date, 1) %></b> which would return this: Friday, July 14, 2012

But you can’t do this:

Wednesday, January 1, 2012

If limitations 1 or 2 are a major hang up for you, you’ll need to use different ASP/VBScript techniques to add the date to your page. I’ll cover those in my next article!

Limitation 3: The time isn’t necessarily “their” time.

Limitation 3 is more of a by-product than a limitation, but I figured I would keep the naming conventions the same for this section. If you use the the FormatDateTime() function (or any other date related function) on the server side, the date/time returned will be whatever the server’s date and time is, not your client’s time from their system.

If you want to ensure that the date and/or time a visitor sees on your page is the date in their part of the coutry or world, then consider using client side VBScript as an Internet Explorer only solution, or switch to client side JavaScript for a universal browser solution.

Limitation 4: It’s static.

Think of the displayed date or time as a “snap shot” of when the page was requested by the visitor. You cant use this function to display a “clock” that updates every second, or automatically update the date on the page when one day turns to the next.

If you wanted to display a dynamic clock on your page, you would need to use client side JavaScript, or VBScript (IE only) to handle that task.

I hope you’ve enjoyed this article on the FormatDateTime() function. I’ll be back soon with more date and time related ASP fun!