VBA string with milliseconds to date

前端 未结 5 788
无人共我
无人共我 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:36

    Michael's answer has an error (as spotted by Jim) when the decimal part rounds up.

    The following corrects the error (slightly modified for tenths of seconds rather than milliseconds and with a parameterized format pattern).

    Public Function FormatDateEx(dt As Currency, formatPattern As String) As String
        Rem FormatDateEx = Format(dt / 86400, "yyyy-mm-dd HH:mm:ss") & "." & ((dt - Fix(dt)) * 1000)
        Dim decimalPart As Double
        decimalPart = Round(((dt - Fix(dt)) * 10), 0)
        If (decimalPart = 10) Then
            FormatDateEx = format(dt / 86400, formatPattern) & ".0"
        Else
            FormatDateEx = format(Fix(dt) / 86400, formatPattern) & "." & decimalPart
        End If
    End Function
    

提交回复
热议问题