About Me

Saturday, 21 April 2012

ASP Dates

ASP Dates

This lesson will teach you how to use the ASP Date Function, how to convert an ASP Date to a String and how to format an ASP Date.

ASP Date Function

The ASP Date function has to be one of the easiest date retrieval methods of all time. To display the date on your page all you need to do is place the Date function as the Response.Write argument.

ASP Code:

<%
Response.Write(Date())
%>

Display:

4/21/2012
You can even use some shorthand techniques to make printing out the current date to your web page only one line of ASP Code. See our ASP Special Characters Lesson for more information.

ASP Code:

<%=Date%>

Display:

4/21/2012
Pretty sweet.

Convert ASP Date to String

The conversion of an ASP Date to string is unnecessary. If you want to use the Date in a string simply concatenate it onto the string or use the write function as we have above and you're done.
However, if you want to use ASP to format a date into a specific form other than the default format of DD/MM/YYYY (D = day, M = Month, Y = Year) then you will need to use the FormatDateString function. This function is covered in the next section.
If you want to convert a string to date format, check out our String to Date lesson.

FormatDateTime Function

The Format Date Time function takes two arguments: a date and (optional) an integer from 0 through 4. The meanings of these numbers are as follows:
  • 0 - This is the default setting. A short date DD/MM/YYYY will be used.
  • 1 - A long date defined by the computer's regional settings.
  • 2 - A short date defined by the regional settings.
  • 3 - (time)A time using the time format defined by the regional settings.
  • 4 - (time)A time using military time HH:MM (H = hour, M = Minute)
Below is an example of all five used to format the Date function.

ASP Code:

<%
Response.Write("0 = " & FormatDateTime(Date, 0))
Response.Write("<br />1 = " & FormatDateTime(Date, 1))
Response.Write("<br />2 = " & FormatDateTime(Date, 2))
Response.Write("<br />3 = " & FormatDateTime(Date, 3))
Response.Write("<br />4 = " & FormatDateTime(Date, 4))

%>

Display:

0 = 4/21/2012
1 = Friday, October 21, 2005
2 = 4/21/2012
3 = 12:00:00 AM
4 = 00:00
You'll notice that the last two options are pretty worthless if you are just working with a standard date, but they are useful for formatting ASP's Time.

0 comments:

Post a Comment