【问题标题】:VBA SystemTime - 30 daysVBA 系统时间 - 30 天
【发布时间】:2017-05-16 16:12:56
【问题描述】:

我正在处理以前开发人员的代码。此代码已设置 SystemTime。 有没有办法以这种格式获取今天的日期和负 30 天?

代码如下:

Public Function GetIsoTimestampTest() As String
Dim st As SYSTEMTIME

'Get the local date and time
GetSystemTime st

'Format the result
GetIsoTimestampTest = _
    Format$(st.wYear, "0000") & "-" & _
    Format$(st.wMonth, "00") & "-" & _
    Format$(st.wDay, "00") & "T" & _
    Format$(st.wHour, "00") & ":" & _
    Format$(st.wMinute, "00") & ":" & _
    Format$(st.wSecond, "00") & "Z"
End Function

【问题讨论】:

    标签: ms-access vba systemtime


    【解决方案1】:

    构建原生日期和时间,添加 -30 天,格式化为字符串:

    utcInIsoFormat = Format$(DateAdd("d", -30, _
        DateSerial(st.wYear, st.wMonth, st.wDay) _
        + TimeSerial(st.wHour, st.wMinute, st.wSecond)), "yyyy-mm-ddThh:nn:ssZ")
    

    【讨论】:

      【解决方案2】:

      SYSTEMTIME 似乎是您代码中其他地方定义的自定义类型。它不是 Access VBA 中可用的标准类型。所以要有效地使用它,你需要找到定义。此外,GetSystemTime 也可能是您的代码独有的自定义函数。这是一个类似类型的示例定义,尽管它可能与您的系统中实现的不完全一样:http://custom-designed-databases.com/wordpress/2011/get-milliseconds-or-seconds-from-system-time-with-vba/

      也就是说,系统时间是指 Windows 系统时间。您还可以在 VBA 中使用 Now() 函数来获取时间。 (https://msdn.microsoft.com/en-us/library/office/gg278671.aspx) 这会返回一个 Date 类型的变量,它相当于一个数字,其中整数表示天,小数表示一天中的时间。获取今天前 30 天的示例如下:

      Dim lastMonth as Date
      Dim formattedDate as String    
      
      lastMonth = Now() - 30
      formattedDate = Format(lastMonth, "yyyy-mm-ddThh:nn:ssZ")
      

      【讨论】:

      • GetSystemTime() 是一个平台API,它以UTC返回当前时间。
      • 但它本身在 Access VBA 中不可用。您必须创建一个函数才能按照 OP 描述的方式访问它。
      • 你只需要声明它,关键是它返回UTC时间,不像Now()是当地时间。
      【解决方案3】:

      DateSerial 很乐意接受负的天数。因此:

      Public Function IsoDateMinus30() As Date
      
          Dim st As SYSTEMTIME
          Dim Result As Date
      
          ' Get the local date and time
          GetSystemTime st
      
          Result = DateSerial(st.wYear, st.wMonth, st.wDay - 30)
      
          ' To include time:
          '
          ' Result = _
          '     DateSerial(st.wYear, st.wMonth, st.wDay - 30) + _
          '     TimeSerial(st.wHour, st.wMinute, st.wSecond)    
      
          IsoDateMinus30 = Result
      
      End Function
      

      【讨论】:

        猜你喜欢
        • 2019-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-02
        相关资源
        最近更新 更多