VBA string with milliseconds to date

前端 未结 5 730
无人共我
无人共我 2021-01-19 21:38

I have a string in the form \"yyyy-mm-dd hh:mm:ss.mmm\" (where the end is milliseconds)

I\'d like to convert it to a number, preferably a Date

5条回答
  •  旧巷少年郎
    2021-01-19 22:31

    The code below contains all the components you might need to manage your dates and their milliseconds.

    Private Sub ParseTime()
    
        Dim strTime As String
        Dim Sp() As String
        Dim Dt As Double
    
        strTime = "2017-12-23 10:29:15.221"
        Sp = Split(strTime, ".")
        strTime = Sp(0)
    
        Dt = CDbl(CDate(strTime))
        strTime = "yyyy-mm-dd hh:mm:ss"
        If UBound(Sp) Then
            Dt = Dt + CDbl(Sp(1)) * 1 / 24 / 60 / 60 / (10 ^ Len(Sp(1)))
            strTime = strTime & "." & CInt(Sp(1))
        End If
        Debug.Print Format(Dt, strTime)
    End Sub
    

    I can't say that I am entirely happy with the solution because the print is only implicitly equal to the date value. However, I found that the formerly valid Date/Time format, like "yyyy-mm-dd hh:mm:ss.000", doesn't seem to work since 2007. However, it should be possible to prove conclusively that the Date/Time value is equal to its rendering by the format mask I includedcd above.

提交回复
热议问题