在ASP中,可以使用VBScript的
Now()函数获取当前时间。,``asp,,``获取当前时间的方法
在ASP(Active Server Pages)中,可以使用VBScript或JScript脚本语言来获取当前时间,以下是使用VBScript获取当前时间的几种常见方法:

1. 使用Now函数
Now是VBScript中的一个内置函数,用于返回当前的日期和时间。
<%
Dim currentTime
currentTime = Now()
Response.Write("当前时间: " & currentTime)
%>
2. 使用Date函数和Time函数
如果你只想获取当前的日期或时间,可以使用Date和Time函数分别获取。
<%
Dim currentDate, currentTimeOnly
currentDate = Date()
currentTimeOnly = Time()
Response.Write("当前日期: " & currentDate & "<br>")
Response.Write("当前时间: " & currentTimeOnly)
%>
3. 格式化当前时间

你可以使用FormatDateTime函数来格式化日期和时间。
<%
Dim formattedTime
formattedTime = FormatDateTime(Now(), vbGeneralDate)
Response.Write("格式化后的时间: " & formattedTime)
%>
4. 转换为字符串表示
有时候你可能需要将当前时间转换为特定的字符串格式,YYYY-MM-DD HH:MM:SS”。
<%
Dim currentTimeStr
currentTimeStr = Year(Now()) & "-" & Right("0" & Month(Now()), 2) & "-" & Right("0" & Day(Now()), 2) & " " & Right("0" & Hour(Now()), 2) & ":" & Right("0" & Minute(Now()), 2) & ":" & Right("0" & Second(Now()), 2)
Response.Write("自定义格式的时间: " & currentTimeStr)
%>
表格形式展示不同方法
| 方法名称 | 代码示例 | 输出结果 |
Now函数 |
<% |
当前时间: mm/dd/yyyy hh:mm:ss |
Date和Time函数 |
<% |
当前日期: mm/dd/yyyy 当前时间: hh:mm:ss |
FormatDateTime函数 |
<% |
格式化后的时间: mm/dd/yyyy hh:mm:ss |
| 自定义字符串格式 | <% |
自定义格式的时间: yyyy-mm-dd hh:mm:ss |
相关问答FAQs
Q1: 如何在ASP中使用JavaScript获取当前时间?
A1: 在ASP页面中嵌入JavaScript代码,可以使用new Date()对象来获取当前时间,以下是一个示例:

<%@ Language="VBScript" %>
<!DOCTYPE html>
<html>
<head>
<title>获取当前时间</title>
<script type="text/javascript">
function getCurrentTime() {
var now = new Date();
var timeString = now.toLocaleString();
document.getElementById("timeDisplay").innerHTML = "当前时间: " + timeString;
}
</script>
</head>
<body onload="getCurrentTime()">
<div id="timeDisplay"></div>
</body>
</html>
在这个例子中,当页面加载时,JavaScript函数getCurrentTime会被调用,并将当前时间显示在页面上的一个div元素中。
Q2: 如何在ASP中将当前时间存储到数据库中?
A2: 要将当前时间存储到数据库中,首先需要获取当前时间,然后将其插入到数据库表中,以下是一个示例,假设你使用的是SQL Server数据库:
<%
Dim conn, connString, sql, currentTime
Set conn = Server.CreateObject("ADODB.Connection")
connString = "Provider=SQLOLEDB;Data Source=your_server_name;Initial Catalog=your_database_name;User ID=your_username;Password=your_password"
conn.Open connString
currentTime = Now()
sql = "INSERT INTO your_table_name (datetime_column) VALUES (?)"
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = sql
cmd.Parameters.Append(cmd.CreateParameter("@datetime_param", adDBTimeStamp, adParamInput, , currentTime))
cmd.Execute
cmd.Close
Set cmd = Nothing
conn.Close
Set conn = Nothing
Response.Write("当前时间已成功存储到数据库中。")
%>
在这个例子中,我们首先创建了一个数据库连接,然后获取当前时间并将其插入到名为your_table_name的表中的datetime_column列中,请根据实际情况替换连接字符串中的参数以及表名和列名。