微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VBA 字符串到日期转换,并从 now() 计算差异

如何解决VBA 字符串到日期转换,并从 now() 计算差异

我正在尝试使用非常简单的 VBA 代码转换为日期时间

Sub datetimedifffference()
Dim d As String
Dim sd As Date
d = "2021-04-06T12:56:16+0000"

sd = Format(CDate(d),"mm-dd-yyyy hh:mm:ss")
Debug.Print sd
End Sub

但它给出了类型不匹配错误 任何帮助将不胜感激

我在下面再次尝试,但时间差正在减少而不是增加

Sub datetimedifffference()
Dim d As String
Dim sd As Long
d = "2021-04-06T12:56:16+0000"


sd = DateDiff("n",Now,Format(convertStringtoDate(d))

Debug.Print sd
End Sub


Function convertStringtoDate(stringdate As String) As String
    Dim strings() As String
    strings = Split(stringdate,"T")
 
    convertStringtoDate = strings(0) & " " & Left(strings(1),8)
    'Debug.Print convertStringtoDate
End Function

解决方法

T+0000 应该被替换。另请注意,日期是数字,格式化的日期是字符串。

Sub datetimedifffference()
    Dim d As String
    Dim sd As Date
    
    d = "2021-04-06T12:56:16+0000"
    d = Replace(d,"T"," ")
    d = Replace(d,"+0000","")

    sd = CDate(d)
    Debug.Print sd
End Sub
,

看看你的编辑,我认为你需要改变两个日期的顺序:

Sub datetimedifffference()
  Dim d As String
  Dim sd As Long
  d = "2021-04-06T12:56:16+0000"
  sd = DateDiff("n",convertStringtoDate(d),Now)
  Debug.Print sd
End Sub

Function convertStringtoDate(stringdate As String) As String
  Dim strings() As String
  strings = Split(stringdate,"T")
  convertStringtoDate = CDate(strings(0) & " " & Left(strings(1),8))
End Function
,

您可以使用这个通用函数:

' Converts an ISO 8601 formatted date/time string to a date value.
'
' A timezone info is ignored.
' Optionally,a millisecond part can be ignored.
'
' Examples:
'   2029-02-17T19:43:08 +01.00  -> 2029-02-17 19:43:08
'   2029-02-17T19:43:08         -> 2029-02-17 19:43:08
'   ' IgnoreMilliseconds = False
'   2029-02-17T19:43:08.566     -> 2029-02-17 19:43:08.566
'   ' IgnoreMilliseconds = True
'   2029-02-17T19:43:08.566     -> 2029-02-17 19:43:08.000
'
' 2017-05-24. Gustav Brock. Cactus Data ApS,CPH.
'
Public Function CDateIso8601( _
    ByVal Expression As String,_
    Optional ByVal IgnoreMilliseconds As Boolean) _
    As Date

    Const Iso8601Separator  As String = "T"
    Const NeutralSeparator  As String = " "

    ' Length of ISO 8601 date/time string like: 2029-02-17T19:43:08 [+00.00]
    Const Iso8601Length     As Integer = 19
    ' Length of ISO 8601 date/time string like: 2029-02-17T19:43:08.566
    Const Iso8601MsecLength As Integer = 23
    
    Dim Value       As String
    Dim Result      As Date
    
    Value = Replace(Expression,Iso8601Separator,NeutralSeparator)
    If InStr(Expression,MillisecondSeparator) <> Iso8601Length + 1 Then
        IgnoreMilliseconds = True
    End If
    
    If IgnoreMilliseconds = False Then
        Result = CDateMsec(Left(Value,Iso8601MsecLength))
    Else
        Result = CDate(Left(Value,Iso8601Length))
    End If
    
    CDateIso8601 = Result
    
End Function

然后将您的格式应用于返回的值。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。