Write for Us
SOLUTION 3 - Use a Custom VB Function
Apparently, the only way to do this is to do it ourselves with a custom VB function that infers the milliseconds using a moderately complex algorithm (see below).
But the results are right on, as you can see from this example:
? FormatDateTimeWithMS(rs(0))
20020809 23:15:27:490
Heres the code for this custom VB function. I hope you find it useful.
Public Function FormatDateTimeWithMS(ByVal dDate As Date, Optional strFormat)
Dim lMilliseconds As LongDim bSecondRoundedToUpper As BooleanlMilliseconds = GetMilliseconds(dDate, bSecondRoundedToUpper)
' if the second gets rounded to upper substract one secondIf bSecondRoundedToUpper ThendDate = DateAdd("s", -1, dDate)End If
' check of the strFormat is missingIf Not IsMissing(strFormat) ThenFormatDateTimeWithMS = Format(dDate, strFormat)ElseFormatDateTimeWithMS = Format(dDate, "yyyymmdd Hh:Nn:Ss") ' You can add your own formatEnd If
FormatDateTimeWithMS = FormatDateTimeWithMS & ":" & Format(lMilliseconds, "000000")
End Function
Public Function GetMilliseconds(dOriginalDate As Date, ByRef bSecondRoundedToUpper As Boolean) As Long
' get the string (without milliseconds)Dim strDateTime As StringstrDateTime = CStr(dOriginalDate)
' return it to the datetime (this one doesn't have milliseconds)Dim dRoundedDateTime As DatedRoundedDateTime = CDate(strDateTime)
' check if we're below the zeroIf dOriginalDate > 0 Then' check if the rounded date is after the originalIf dRoundedDateTime > dOriginalDate Then' substract one seconddRoundedDateTime = DateAdd("s", -1, dRoundedDateTime)
' return the flag set to onbSecondRoundedToUpper = TrueElse' return the flag set to offbSecondRoundedToUpper = FalseEnd IfElse' check if the rounded date is before the originalIf dRoundedDateTime < dOriginalDate Then' add one second (by deducting it! - bug in VB?)dRoundedDateTime = DateAdd("s", -1, dRoundedDateTime)
' return the flag set to onbSecondRoundedToUpper = TrueElse' return the flag set to offbSecondRoundedToUpper = FalseEnd If
End If
' milliseconds are the number of ms in one day by the difference of the rounded and the orignal dateGetMilliseconds = 86400000 * Abs(dOriginalDate - dRoundedDateTime)End Function
' TEST SUBPublic Sub TestMilliseconds
Dim cn As New ADODB.Connectioncn.ConnectionString = "driver={SQL Server};server=(local);uid=sa;pwd=q;database=pubs"cn.Open
Dim cm As New ADODB.CommandSet cm.ActiveConnection = cncm.CommandText = "select getdate(), convert(varchar,getdate(),21)"cm.CommandType = adCmdText
Dim rs As ADODB.RecordsetSet rs = cm.Execute
Dim strVBFormat As StringstrVBFormat = FormatDateTimeWithMS(rs(0).Value)
MsgBox "SERVER FORMAT: " & rs(1).Value & vbCrLf & "VB FORMAT: " & strVBFormat
End Sub
Published with the express written permission of the author. Copyright 2002