在VBScript中格式化当前日期和时间

时间:2014-03-22 06:03:26

标签: datetime vbscript asp-classic

我想知道是否有人可以帮助我。

我是ASP的新手我想格式化当前的日期和时间如下:

yyyy-mm-dd hh:mm:ss

但我能做的就是以下

Response.Write Date

请有人帮帮我。

1 个答案:

答案 0 :(得分:25)

默认情况下,日期格式化选项在经典ASP中受限制,有一个函数FormatDateTime()可以根据服务器区域设置以各种方式格式化您的日期。

虽然有内置的日期时间功能,但可以更好地控制日期格式

  • Year(date) - 返回表示年份的整数。通过Date()将返回当前年份。

  • Month(date) - 返回1到12之间的整数,包括1和12,代表一年中的月份。传递Date()将返回当年的当前月份。

  • MonthName(month[, abbv]) - 返回表示指定月份的字符串。作为月份传递Month(Date())将返回当前的Month字符串。 根据@Martha

  • 的建议
  • Day(date) - 返回1到31之间的整数,包括1和31,表示该月的某天。传递Date()将返回当月的当天。

  • Hour(time) - 返回0到23之间的整数,表示当天的小时数。传递Time()将返回当前时间。

  • Minute(time) - 返回0到59之间的整数,包括小时,表示小时的分钟。传递Time()将返回当前分钟。

  • Second(time) - 返回0到59之间的整数,包括0到59,表示分钟的第二个。传递Time()将返回当前秒。

函数Month()Day()Hour()Minute()Second()都返回整数。幸运的是,有一个简单的解决方法,可让您快速填充这些值Right("00" & value, 2)它所做的是将00追加到值的前面,然后从右边取前两个字符。这可确保所有单个数字值的前缀为0

Dim dd, mm, yy, hh, nn, ss
Dim datevalue, timevalue, dtsnow, dtsvalue

'Store DateTimeStamp once.
dtsnow = Now()

'Individual date components
dd = Right("00" & Day(dtsnow), 2)
mm = Right("00" & Month(dtsnow), 2)
yy = Year(dtsnow)
hh = Right("00" & Hour(dtsnow), 2)
nn = Right("00" & Minute(dtsnow), 2)
ss = Right("00" & Second(dtsnow), 2)

'Build the date string in the format yyyy-mm-dd
datevalue = yy & "-" & mm & "-" & dd
'Build the time string in the format hh:mm:ss
timevalue = hh & ":" & nn & ":" & ss
'Concatenate both together to build the timestamp yyyy-mm-dd hh:mm:ss
dtsvalue = datevalue & " " & timevalue

Call Response.Write(dtsvalue)

注意: 您可以在一次调用中构建日期字符串,但决定将其分解为三个变量,以便于阅读。