VBA string with milliseconds to date

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

    A Date type holds the number of days since December 30 1899 with a precision of one second. Though it's still possible to hold the milliseconds by storing the date in a currency type since it can hold 4 extra digits compared to a Date/Double.

    So an alternative would be to store the date as a timestamp in a Currency type representing the number of seconds since December 30 1899:

    Public Function CDateEx(text As String) As Currency
        Dim parts() As String
        parts = Split(text, ".")
        CDateEx = CCur(CDate(parts(0)) * 86400) + CCur(parts(1) / 1000)
    End Function
    

    And to convert the timestamp back to a string:

    Public Function FormatDateEx(dt As Currency) As String
        FormatDateEx = Format(dt / 86400, "yyyy-mm-dd HH:mm:ss") & "." & ((dt - Fix(dt)) * 1000)
    End Function
    

提交回复
热议问题