You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Basic如何向API发送包含动态当前日期时间的JSON对象

VB代码修改方案

你只需要使用VB内置的Now()函数获取当前时间,再通过Format()函数格式化为API要求的yyyy-MM-dd HH:mm:ss格式,再拼接进JSON字符串即可,修改后的完整代码如下:

Dim xhr As Object
' 声明动态日期时间变量
Dim currentDt As String
' 格式化当前时间为API要求的字符串格式
currentDt = Format(Now(), "yyyy-MM-dd HH:mm:ss")

Set xhr = CreateObject("MSXML2.ServerXMLHTTP")
xhr.Open "POST", "https://tenanttest.api.rubixpark.com/api/v1/sales", False

xhr.setRequestHeader "Content-Type", "application/json"
xhr.setRequestHeader "Authorization", "Bearer " + accesstoken
' 拼接动态日期时间到JSON字符串中
xhr.send "[{""datetime"": """ & currentDt & """,""isRefund"": false," & _
         """receiptNumber"": ""880090"",""amount"": 164.22}]"

If xhr.Status = 200 Then
    MsgBox xhr.ResponseText
End If

关键改动说明

  • 时间格式化部分使用Format(Now(), "yyyy-MM-dd HH:mm:ss")强制指定输出格式,不会受系统区域设置影响,保证输出的时间字符串完全符合API的要求
  • 拼接JSON时注意动态变量需要用""" & 变量名 & """包裹,也就是前后各三个双引号,才能正确生成JSON要求的带双引号的字符串值

如果需要发送UTC时间而非本地时间,可以新增时区偏移处理逻辑,替换时间格式化部分即可:

' 获取UTC时间
Dim utcDt As Date
utcDt = DateAdd("h", -GetTimeZoneOffset(), Now())
currentDt = Format(utcDt, "yyyy-MM-dd HH:mm:ss")

' 补充获取时区偏移的辅助函数
Function GetTimeZoneOffset() As Integer
    Dim oShell As Object
    Set oShell = CreateObject("WScript.Shell")
    GetTimeZoneOffset = oShell.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias") / 60
End Function

内容的提问来源于stack exchange,提问作者Mohamed hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 16:09:02