ASP Code
  Home arrow ASP Code arrow Format Date/Time Function - fmtDateTime() ...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP CODE

Format Date/Time Function - fmtDateTime() by Kevin Turner
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 19
    2001-07-21

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Format Date/Time Function - fmtDateTime()
     
    This function was created to compensate for the poor date and time formatting capabilities available to the ASP (VBScript) developer. FormatDateTime() just doesn't cut it! This function is analgous to the Format() function in the Visual Basic world.
     
    The function takes two parameters:
    1. A valid date object
    2. A formatting string such as 'mm-dd-yyyy'
     
    Usage:
     
    The first parameter can be a Variant Date object or an expression that evaluated to Variant Date object. The second parameter is a Variant String composed of the following date and time tokens:
     
    Date Parts
    • yy - year value, 2-digits
    • yyyy - year value, 4-digits
    • m - month value (1 to 12), not zero-padded
    • mm - month value (1 to 12), zero-padded
    • d - day value (1 to 31), not zero-padded
    • dd - day value (1 to 31), zero-padded
    Time Parts
    • h - hours value, not zero-padded
    • hh - hours value, zero-padded
    • m or mm - minutes value, always zero-padded
    • s or ss - seconds value, always zero-padded
    Acceptable time delimiters:
    • colon (:)
    Acceptable date delimiters:
    • forward slash(/)
    • hyphen (-)
    If you to use date and time formatting, then separate the date from the time with a space.
     
    Note: fmrDateTime requires a small utility function called ZeroPads to -- you guessed it -- zero-pad values. It is included below.
     
    Example:
     
    <%
    Dim dToday, dXmas2001
    Response.Write "Today's date: " & fmtDateTime(Now(), "yyyy-mm-dd")
    ' date displayed: 2001-07-19
    Response.Write "Yesterday's date: " & fmtDateTime(DateAdd("d", -1,
    Now()), "yyyy-mm-dd") ' date displayed: 2001-07-18 dXmas2001 = #12/25/2001 12:45:50# Response.Write "Christmas 2001: : " & fmtDateTime(dXmas2001,
    "m/dd/yyyy hh:mm") ' date/time displayed: 12/25/2001 12:45 %>
     
    Here is the code:
    <%
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Routine:   fmtDateTime()
    '
    ' Purpose:   Returns a Variant (String) containing an expression 
    '            formatted according to instructions contained in a 
    '            format expression
    '
    ' Inputs :   Argument    : d
    '            DataType    : Variant Date
    '            Description : A *valid* variant date variable or an
    '                        : expression that result in a variant date
    '                        : variable
    '
    '            Argument    : pat
    '            DataType    : Variant String
    '            Description : An acceptable date and/or time pattern
    '
    ' Outputs:   Argument    : None
    '
    ' Returns:   Formatted Variant string representation of the date
    '            passed in or an error message where applicable.
    '
    ' Sample Usage :
    '  strToday = fmtDateTime(Now(), "yyyy-mm-dd hh:mm:ss")
    '  strYesterday = fmtDateTime(DateAdd("d", -1, Now()), "h:m:s")
    '
    ' Author :   Kevin J. Turner  July 11, 2001
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Function fmtDateTime(byval d, byval pat)
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Acceptable date formatting parts:
    '  yy       - year value, 2-digits
    '  yyyy     - year value, 4-digits
    '  m        - month value (1 to 12), not zero-padded
    '  mm       - month value (1 to 12), zero-padded
    '  d        - day value (1 to 31), not zero-padded
    '  dd       - day value (1 to 31), zero-padded
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Acceptable time formatting parts:
    '  h        - hours value, not zero-padded
    '  hh       - hours value, zero-padded
    '  m or mm  - minutes value, always zero-padded
    '  s or ss  - seconds value, always zero-padded
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Acceptable time delimiters:
    '   colon (:)
    ' Acceptable date delimiters:    
    '   space ( ) or hyphen (-)
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Assumptions made: 
    ' DATE-ONLY patterns will NOT contain colons or spaces
    ' TIME-ONLY patterns will NOT contain hyphens or forward slashes
    '   and WILL contain colons
    ' DATE-TIME patterns WILL contain acceptable date part delimiters,
    '   acceptable time part delimiters, and a space to delimit the 
    '   date from the time
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    ' First, if a space character is present, then the patteren is 
    ' split into a 2-element array: the first element being (typically)
    ' the date portion, and the second element being (typically) the 
    ' time portion. If no space character present, then we're working 
    ' with a date or time part. Splitting this type of pattern with 
    ' double-quotes ("") will result in a 1-element array consisting 
    ' of a date portion or a time portion.
    Dim Tokens, token, delim, i, date_part, time_part, DateTokens, TimeTokens
    ' do not treat Null values as erroneous parameters, handle them gracefully
    If IsNull(d) Then
    fmtDateTime = ""
    Exit Function
    End If
    If TypeName(d) <> "Date" Or Not IsDate(d) Then
    fmtDateTime = "Invalid date parameter."
    Exit Function
    End If
    ' if there's a space in the string, then we're dealing with 
    ' date *and* time formatting, otherwise it date OR time formatting
    ' we doing
    If InStr(pat, " ") > 0 Then
    Tokens = Split(pat, " ") ' should be 2 tokens --> (0)date (1)time
    Else
    Tokens = Split(pat, "") ' date OR time formatting
    End If
    bIsDate = False : bIsTime = False
    For Each token In Tokens
    If InStr(token, "-") > 0 Or InStr(token, "/") > 0 Then
    ' get the delimter used...
    If InStr(token, "-") Then
    delim = "-"
    ElseIf InStr(token, "/") Then
    delim = "/"
    End If
    ' tokenize the date parts
    DateTokens = Split(token, delim)
    For i = 0 To UBound(DateTokens)
    ' replace the time tokens with properly formatted values
    Select Case CStr(DateTokens(i))
    Case "yy"
    DateTokens(i) = Right(CStr(DatePart("yyyy", d)), 2)
    Case "yyyy"
    DateTokens(i) = CStr(DatePart("yyyy", d))
    Case "m"
    DateTokens(i) = CStr(DatePart("m", d))
    Case "mm"
    DateTokens(i) = ZeroPad(CStr(DatePart("m", d)),2)
    Case "d"
    DateTokens(i) = CStr(DatePart("d", d))
    Case "dd"
    DateTokens(i) = ZeroPad(CStr(DatePart("d", d)),2)
    Case Else
    fmtDateTime = "Invalid date format : " & token
    Exit Function
    End Select
    Next
    date_part = Join(DateTokens, delim)
    End If
    If InStr(token, ":") > 0 Then
    ' tokenize the time parts
    TimeTokens = Split(token, ":")
    For i = 0 To UBound(TimeTokens)
    ' replace the time tokens with properly formatted values
    Select Case CStr(TimeTokens(i))
    Case "h"
    TimeTokens(i) = Right(CStr(DatePart("h", d)), 2)
    Case "hh"
    TimeTokens(i) = ZeroPad(CStr(DatePart("h", d)),2)
    Case "m", "mm"  ' always zero-pad minutes
    TimeTokens(i) = ZeroPad(CStr(DatePart("n", d)),2)
    Case "s", "ss"  ' always zero-pad seconds
    TimeTokens(i) = ZeroPad(CStr(DatePart("s", d)),2)
    Case Else
    fmtDateTime = "Invalid time format : " & token
    Exit Function
    End Select
    Next
    time_part = Join(TimeTokens, ":")
    End If
    Next
    fmtDateTime =  Trim(date_part & " " & time_part)
    End Function
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Routine:   ZeroPad()
    '
    ' Purpose:   Pads a Variant String with zeros to a specified number
    '            of digits, 
    '               e.g.  "12" padded to 4 digits --> "0012"
    '
    ' Inputs :   Argument    : str
    '            DataType    : Variant String
    '            Description : The string value to be padded
    '
    '            Argument    : iSize
    '            DataType    : Variant Integer
    '            Description : The total desired size of the returned
    '                          string.
    '
    ' Outputs:   Argument    : None
    '
    ' Returns:   A zero-padded Variant string representation of the string
    '            passed in.
    '
    ' Sample Usage :
    '  strVal = ZeroPad("14", 4)  ' <--  returns "0014"
    '
    ' Author :   Kevin J. Turner  July 11, 2001
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Function ZeroPad(byval str, byval iSize)
    ZeroPad = String((iSize - Len(str)), "0") & Trim(str)
    End Function
    %>
    

    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP Code Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    IBM – Taking Web 2.0 to Work

    You'll get answers to many questions and more from David Barnes, Lead Evangelist for IBM Emerging Internet Technologies. David will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! "ebook: Exploring IBM SOA Technology & Practice

    Learn field-tested SOA principles, methodology, technology and implementation from the global SOA market leader - in a new e-book by an IBM SOA expert. Written by IBM Certified SOA Solution Designer Bobby Woolf, "Exploring IBM SOA Technology & Practice" is the ultimate insider's guide to SOA - a PDF e-book packed cover to cover with IBM's specific advice on how to make your SOA implementation a success.
    FREE! Go There Now!


    NEW! Accelerating Software Innovation on i on Power Systems

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Krugle, developerWorks, and code search

    Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users.
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    NEW! Rational Talks to You: Scott Ambler on being agile in a global development environment

    Join this Rational Talks to You teleconference on December 6 at 1:00 pm ET to participate in an agile application development discussion and get your questions answered on using IBM Rational Method Composer in a distributed environment.Get your questions answered!
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs).
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for People

    Visit IBM developerWorks to try the IBM SOA Sandbox for people. The SOA Sandbox for people provides a trial environment with the necessary tooling and components required to enable consistent human and process interaction and collaboration, showing how you can improve user experience and business productivity.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP CODE ARTICLES

    - ASP Forms
    - ASP: The Beginning
    - Getting Remote Files With ASP Continued
    - Inbox and Outbox Manipulation in ASP
    - Relational DropDownList Using VB.NET
    - Ad Tracking URL Hits
    - Use ViewState to display one record per page...
    - Send Email using ASP.NET formatted in HTML
    - ASP File Explorer
    - ASP/XML Interview questions by Srivatsan Sri...
    - Various methods of setting Date values to a ...
    - Conditional DataGrid Item and using checkbox...
    - Fill .NET Listbox with SQL DataReader
    - Filling Dropdown box using Code-Behinds in C#
    - FLAMES code sample written in .NET What is F...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway