How to Custom Date Formatting in VBScript – ASP Classic

FormatDateTime

ASP Classic provides FormatDateTime function which allows you to format a valid date or time expression. For date, it allows you to select two formats: vbLongDate, and vbShortDate. The syntax is as follows:

FormatDateTime(date,format)
Parameter Description
date Required. Any valid date expression (like Date() or Now())
format Optional. A value that specifies the date/time format to use
Can take the following values:

  • 0 = vbGeneralDate – Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
  • 1 = vbLongDate – Returns date: weekday, monthname, year
  • 2 = vbShortDate – Returns date: mm/dd/yy
  • 3 = vbLongTime – Returns time: hh:mm:ss PM/AM
  • 4 = vbShortTime – Return time: hh:mm

Reference: http://www.w3schools.com/vbscript/func_formatdatetime.asp

Example

<%
	Response.write(FormatDateTime(Now(),1) & "<br />")
	Response.write(FormatDateTime(Now(),2) & "<br />")
%>

The result will be:

Sunday, July 14, 2013
7/14/2013

Custom Date Formatting

Sometimes, you want to customize in other common date formats, such as, YYYYMMDD, YYYY-MM-DD, MMDDYYYY, etc. You can use the function below to generate your custom date format as you want.

<% 
    Function pd(n, totalDigits) 
        if totalDigits > len(n) then 
            pd = String(totalDigits-len(n),"0") & n 
        else 
            pd = n 
        end if 
    End Function 
%>

YYYYMMDD

<% 
    response.write YEAR(Date()) & _ 
        Pd(Month(date()),2) & _ 
        Pd(DAY(date()),2) 
%>

YYYY-MM-DD

This is common format used for storing DATE data type in MySQL and SQL Server.

<% 
    response.write YEAR(Date()) & _ 
        "-" & Pd(Month(date()),2) & _ 
        "-" & Pd(DAY(date()),2) 
%>

DDMMYYYY

<% 
    response.write Pd(DAY(date()),2) & _ 
        Pd(Month(date()),2) & _ 
        YEAR(Date()) 
%>

MMDDYYYY

<% 
    response.write Pd(Month(date()),2) & _ 
        Pd(DAY(date()),2) & _ 
        YEAR(Date()) 
%>

DD-MM-YY

<% 
    response.write pd(DAY(date()),2) & "-" & _ 
        pd(MONTH(date()),2) & "-" & _ 
        pd(RIGHT(YEAR(date()),2),2) 
%>

YY-MM-DD

<% 
    response.write pd(RIGHT(YEAR(date()),2),2) & "-" & _ 
        pd(MONTH(date()),2) & "-" & _ 
        pd(DAY(date()),2) 
%>

Reference: http://classicasp.aspfaq.com/date-time-routines-manipulation/can-i-make-vbscript-format-dates-for-me.html

Leave a Reply