我在 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 月的最后一个星期日 ( source ) 的 01:00 UTC 开始从 UTC+1 切换到 UTC+2,但上面的输出显示在 00:00 从 UTC+1 切换到 UTC+2 UTC,这是完全不正确的。我看不出我的代码有什么问题。这是微软代码库中的一个已知错误吗?
最佳答案
这似乎是 TimeZones.ConvertTime
的底层实现中的错误。 Outlook VBA 对象模型中的方法。
使用您问题中的代码,在引用“Microsoft Outlook 16.0 对象库”后,我能够在 VBA 中重现不准确的结果。 OutlookApplication.Version
是 16.0.0.14931
.
使用 .NET TimeZoneInfo
上的转换方法,在同一台 Windows 机器上运行的 .NET 应用程序可以得到正确的结果。目的。据我所知,这使用了 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 实现。我建议opening a support issue with Microsoft如果这对你很重要。你可以引用这个答案。
关于excel - 为什么 outlook.timezones.converttime 会导致 DST 更改错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71616789/