我的应用程序与时间戳一起工作很多。很多时候,我需要切断变量的DDMMYYYY
一部分。Date
第一个猜测是
Dim xDate as Date
Dim xDDMMYYY as Date : xDDMMYYY = Dateserial(Year(xDate), Month(xDate), Day(xDate))
但是,这超级慢。所以相反,我想找到一种更快的方法。首先,我会尝试使用该Floor
功能。所以 ...
Public Function timeStamp2DDMMYYYY(xStamp As Date) As Date
timeStamp2DDMMYYYY = WorksheetFunction.Floor(CDbl(xStamp), 1)
End Function
但是,这会产生错误的结果,例如 1900 年 1 月 4 日,其中函数返回 1900 年 1 月 3 日。所以,我第二次尝试...
Public Function timeStamp2DDMMYYYY(xStamp As Date) As Date
' timeStamp2DDMMYYYY = CDbl(xStamp) - modDblTimeStamps(CDbl(xStamp), 1) ' Cut the non-whole days off
timeStamp2DDMMYYYY = WorksheetFunction.Floor(CDbl(xStamp), 1) ' Cut the non-whole days off
End Function
Private Function modDblTimeStamps(xA As Double, xB As Double) As Double
Dim xRes As Double: xRes = xA - (CLng(xA / xB) * xB)
If (xRes < -1 / 86400) Then xRes = xRes + xB ' A difference between xRes and zero
' must be at least one second to prevent
modDblTimeStamps = xRes
End Function
但是,这会产生不良行为,例如 1963 年 8 月 31 日 23:59:59。
我的问题是:是否有一种快速且故障安全的方法来完成这种转换?
编辑 不好 - 我应该先使用探查器。出于比较目的,我收集了所有建议的解决方案:
Public Function timeStamp2DDMMYYYY_1(xStamp As Date) As Date
timeStamp2DDMMYYYY_1 = DateSerial(Year(xStamp), Month(xStamp), Day(xStamp))
End Function
Public Function timeStamp2DDMMYYYY_2(xStamp As Date) As Date
timeStamp2DDMMYYYY_2 = DateValue(xStamp)
End Function
Public Function timeStamp2DDMMYYYY_3(xStamp As Date) As Date
Dim xDDMMYYY As String: xDDMMYYY = DatePart("d", xStamp) & "." & DatePart("m", xStamp) & "." & DatePart("yyyy", xStamp)
timeStamp2DDMMYYYY_3 = CDate(xDDMMYYY)
End Function
Public Function timeStamp2DDMMYYYY_4(xStamp As Date) As Date
timeStamp2DDMMYYYY_4 = CDate(Split(xStamp, Chr(32))(0))
End Function
Public Function timeStamp2DDMMYYYY_5(xStamp As Date) As Date
timeStamp2DDMMYYYY_5 = CDbl(xStamp) - modDblTimeStamps(CDbl(xStamp), 1)
End Function
Public Function timeStamp2DDMMYYYY_6(xStamp As Date) As Date
timeStamp2DDMMYYYY_6 = Int(xStamp)
End Function
从 01.01.1900 到 31.12.1905,增量为 5 分钟,所有函数都返回正确的值。分析结果是:
timeStamp2DDMMYYYY_1 - 2.22199s
timeStamp2DDMMYYYY_2 - 5.62594s
timeStamp2DDMMYYYY_3 - 5.91005s
timeStamp2DDMMYYYY_4 - 6.51989s
timeStamp2DDMMYYYY_5 - 3.67998s
timeStamp2DDMMYYYY_6 - 4.29623s
结论 - 我的慢点在 timeStampManip 模块的其他地方。原始版本是最快的……谢谢大家。