65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP FormatDate

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.40/5 (8投票s)

2008年5月5日

CPOL
viewsIcon

39997

VBScript / Classic ASP 的日期格式化函数

引言

VBScript 中缺少 Visual Basic 的 Format 函数,该函数用于格式化日期。

如果没有 Format,很难生成自定义格式的日期。

使用下面描述的 FormatDate 函数,您的担忧将迎刃而解!

Using the Code

首先找到格式 字符串 的长度。

接下来,循环遍历格式 字符串 中的每个字符。

开始构建格式块。

当字符发生变化时处理格式块(意味着新的格式块正在开始,或者我们需要保留分隔符字符)。

各种支持的格式块通过 SELECT CASE 语句进行转换,并将输出 字符串 (格式化后的日期)附加到末尾。 语句末尾的 CASE ELSE 语句将附加分隔符字符或任何未被理解为格式块 字符串 的内容。

继续循环,直到超过末尾,并将最终的块或字符处理掉。

Function FormatDate(strDate, strDateFmt)
  dim strRet
  dim i  
  dim formatBlock
  dim formatLength
  dim charLast
  dim charCur
  
  formatLength = len(strDateFmt)
  
  for i = 1 to formatLength + 1
    ' grab the current character
    charCur = mid(strDateFmt, i, 1)
    
    if charCur = charLast then
        ' The block is not finished. 
        ' Continue growing the block and iterate to the next character.
        formatBlock = formatBlock & charCur
    else
        ' we have a change and need to handle the previous block
        select case formatBlock
        case "mmmm"
            strRet = strRet & MonthName(DatePart("m",strDate),False)
        case "mmm"
            strRet = strRet & MonthName(DatePart("m",strDate),True)
        case "mm"
            strRet = strRet & right("0" & DatePart("m",strDate),2)
        case "m"
            strRet = strRet & DatePart("m",strDate)
        case "dddd"
            strRet = strRet & WeekDayName(DatePart("w",strDate,1),False)
        case "ddd"
            strRet = strRet & WeekDayName(DatePart("w",strDate,1),True)
        case "dd"
            strRet = strRet & right("0" & DatePart("d",strDate),2)
        case "d"
            strRet = strRet & DatePart("d",strDate)
        case "o"
            strRet = strRet & intToOrdinal(DatePart("d",strDate))
        case "yyyy"
            strRet = strRet & DatePart("yyyy",strDate)
        case "yy"
            strRet = strRet & right(DatePart("yyyy",strDate),2)
        case "y"
            strRet = strRet & cInt(right(DatePart("yyyy",strDate),2))
        case else
            strRet = strRet & formatBlock
        end select
        ' Block handled.  
        ' Now reset the block and continue iterating to the next character.
        formatBlock = charCur
    end if
    
    charLast = charCur
  next 'i
 
  FormatDate = strRet
End Function

历史

  • 2008/5/5 v1.0
  • 2009/2/13 v2.0
© . All rights reserved.