我在 Excel 中使用以下 VBA 代碼:
Function tzAtotzB(srcDT As Date, srcTZ As String, dstTZ As String) As Date
Dim OutlookApp As Object
Dim TZones As TimeZones
Dim convertedTime As Date
Dim sourceTZ As TimeZone
Dim destTZ As TimeZone
Dim secNum As Integer
Set OutlookApp = CreateObject("Outlook.Application")
Set TZones = OutlookApp.TimeZones
Set destTZ = TZones.Item(dstTZ)
Set sourceTZ = TZones.Item(srcTZ)
tzAtotzB = TZones.ConvertTime(srcDT, sourceTZ, destTZ)
End Function
Function CETtoUTC(srcDT As Date) As Date
CETtoUTC = tzAtotzB(srcDT, "Central Europe Standard Time", "UTC")
End Function
Function UTCtoCET(srcDT As Date) As Date
UTCtoCET = tzAtotzB(srcDT, "UTC", "Central Europe Standard Time")
End Function
由于某種原因,結果不是人們所期望的:
Debug.Print UTCtoCET("26/03/2022 23:00:00")
27/03/2022
Debug.Print UTCtoCET("27/03/2022 00:00:00")
27/03/2022 02:00:00
Debug.Print CETtoUTC("27/03/2022 02:00:00")
27/03/2022
Debug.Print UTCtoCET("28/03/2021 00:00:00")
28/03/2021 02:00:00
CET 應該在 3 月的最后一個星期日 01:00 UTC 開始從 UTC 1 切換到 UTC 2(來源),但上面的輸出顯示了在 00:00 UTC 從 UTC 1 切換到 UTC 2,這是完全不正確的。
我看不出我的代碼有什么問題。這是微軟代碼庫中的一個已知錯誤嗎?
uj5u.com熱心網友回復:
這似乎是TimeZones.ConvertTimeOutlook VBA 物件模型中方法的底層實作中的一個錯誤。
使用您問題中的代碼,在參考“Microsoft Outlook 16.0 物件庫”后,我能夠在 VBA 中重現不準確的結果。OutlookApplication.Version是16.0.0.14931。_
使用.NET物件上的轉換方法,在同一臺 Windows 機器上運行的 .NET 應用程式中可以得到正確的結果。TimeZoneInfo據我所知,這使用了 Windows 注冊表中的時區資料,這與 Outlook VBA 庫使用的資料相同。
這是演示正確結果的 .NET C# 代碼:
var zone = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
var input1 = DateTimeOffset.Parse("2022-03-27T00:00:00Z");
var output1 = TimeZoneInfo.ConvertTime(input1, zone);
Console.WriteLine($"{input1.UtcDateTime:yyyy-MM-dd'T'HH:mm:ssK} => {output1:yyyy-MM-dd'T'HH:mm:sszzz}");
var input2 = DateTimeOffset.Parse("2022-03-27T01:00:00Z");
var output2 = TimeZoneInfo.ConvertTime(input2, zone);
Console.WriteLine($"{input2.UtcDateTime:yyyy-MM-dd'T'HH:mm:ssK} => {output2:yyyy-MM-dd'T'HH:mm:sszzz}");
哪個輸出:
2022-03-27T00:00:00Z => 2022-03-27T01:00:00 01:00
2022-03-27T01:00:00Z => 2022-03-27T03:00:00 02:00
這顯示了正確的轉換,因此資料是正確的。因此,問題必須特定于 Outlook VBA 實作。如果這對您很重要,我建議向 Microsoft 提出支持問題。你可以參考這個答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449918.html
