在 VBA (Excel) 中获取时区信息

2024-03-20

我想在 VBA 中确定不同国家/地区在特定日期的 GMT/UTC 时间偏移(包括夏令时)。有任何想法吗?

编辑(来自自我回答):

谢谢 0xA3。我快速浏览了链接页面。我假设您只能获取 Windows 运行所在本地的 GMT 偏移量:

ConvertLocalToGMT    
DaylightTime  
GetLocalTimeFromGMT          
LocalOffsetFromGMT
SystemTimeToVBTime
LocalOffsetFromGMT

在 Java 中,您可以执行以下操作:

TimeZone bucharestTimeZone = TimeZone.getTimeZone("Europe/Bucharest");
    bucharestTimeZone.getOffset(new Date().getTime());

Calendar nowInBucharest = Calendar.getInstance(TimeZone.getTimeZone("Europe/Bucharest"));
    nowInBucharest.setTime(new Date());
    System.out.println("Bucharest: " + nowInBucharest.get(Calendar.HOUR) + ":" + nowInBucharest.get(Calendar.MINUTE));

这意味着我可以获得不同国家(时区)的偏移量,因此我也可以获得布加勒斯特的实际时间。我可以在 VBA 中执行此操作吗?


VBA 不提供执行此操作的函数,但 Windows API 提供。幸运的是,您也可以使用 VBA 中的所有这些功能。本页描述了如何执行此操作:时区和夏令时 http://www.cpearson.com/excel/TimeZoneAndDaylightTime.aspx


编辑:添加代码

为了后代的利益,我添加了 Guru Chip 页面上的完整代码,可在 32 位 Office VBA 中使用。 (64位修改here https://stackoverflow.com/a/20489651/8112776)

Option Explicit
Option Compare Text
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' modTimeZones
' By Chip Pearson, used with permission from www.cpearson.com
' Date: 2-April-2008
' Page Specific URL: www.cpearson.com/Excel/TimeZoneAndDaylightTime.aspx
'
' This module contains functions related to time zones and GMT times.
'   Terms:
'   -------------------------
'   GMT = Greenwich Mean Time. Many applications use the term
'       UTC (Universal Coordinated Time). GMT and UTC are
'       interchangable in meaning,
'   Local Time = The local "wall clock" time of day, that time that
'       you would set a clock to.
'   DST = Daylight Savings Time

'   Functions In This Module:
'   -------------------------
'       ConvertLocalToGMT
'           Converts a local time to GMT. Optionally adjusts for DST.
'       DaylightTime
'           Returns a value indicating (1) DST is in effect, (2) DST is
'           not in effect, or (3) Windows cannot determine whether DST is
'           in effect.
'       GetLocalTimeFromGMT
'           Converts a GMT Time to a Local Time, optionally adjusting for DST.
'       LocalOffsetFromGMT
'           Returns the number of hours/minutes between the local time &GMT,
'           optionally adjusting for DST.
'       SystemTimeToVBTime
'           Converts a SYSTEMTIME structure to a valid VB/VBA date.
'       LocalOffsetFromGMT
'           Returns the number of minutes or hours that are to be added to
'           the local time to get GMT. Optionally adjusts for DST.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

' Required Types
Private Type SYSTEMTIME
    wYear As Integer
    wMonth As Integer
    wDayOfWeek As Integer
    wDay As Integer
    wHour As Integer
    wMinute As Integer
    wSecond As Integer
    wMilliseconds As Integer
End Type

Private Type TIME_ZONE_INFORMATION
    Bias As Long
    StandardName(0 To 31) As Integer
    StandardDate As SYSTEMTIME
    StandardBias As Long
    DaylightName(0 To 31) As Integer
    DaylightDate As SYSTEMTIME
    DaylightBias As Long
End Type

Public Enum TIME_ZONE
    TIME_ZONE_ID_INVALID = 0
    TIME_ZONE_STANDARD = 1
    TIME_ZONE_DAYLIGHT = 2
End Enum

' Required Windows API Declares
Private Declare Function GetTimeZoneInformation Lib "kernel32" _
    (lpTimeZoneInformation As TIME_ZONE_INFORMATION) As Long

Private Declare Sub GetSystemTime Lib "kernel32" _
    (lpSystemTime As SYSTEMTIME)

Function ConvertLocalToGMT(Optional LocalTime As Date, _
    Optional AdjustForDST As Boolean = False) As Date
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ConvertLocalToGMT
' This converts a local time to GMT. If LocalTime is present, that local
' time is converted to GMT. If LocalTime is omitted, the current time is
' converted from local to GMT. If AdjustForDST is Fasle, no adjustments
' are made to accomodate DST. If AdjustForDST is True, and DST is
' in effect, the time is adjusted for DST by adding
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim T As Date
    Dim TZI As TIME_ZONE_INFORMATION
    Dim DST As TIME_ZONE
    Dim GMT As Date

    If LocalTime <= 0 Then
        T = Now
    Else
        T = LocalTime
    End If
    DST = GetTimeZoneInformation(TZI)
    If AdjustForDST = True Then
        GMT = T + TimeSerial(0, TZI.Bias, 0) + _
                IIf(DST=TIME_ZONE_DAYLIGHT,TimeSerial(0, TZI.DaylightBias,0),0)
    Else
        GMT = T + TimeSerial(0, TZI.Bias, 0)
    End If
    ConvertLocalToGMT = GMT
End Function

Function GetLocalTimeFromGMT(Optional StartTime As Date) As Date
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GetLocalTimeFromGMT
' This returns the Local Time from a GMT time. If StartDate is present and
' greater than 0, it is assumed to be the GMT from which we will calculate
' Local Time. If StartTime is 0 or omitted, it is assumed to be the GMT
' local time.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim GMT As Date
    Dim TZI As TIME_ZONE_INFORMATION
    Dim DST As TIME_ZONE
    Dim LocalTime As Date

    If StartTime <= 0 Then
        GMT = Now
    Else
        GMT = StartTime
    End If
    DST = GetTimeZoneInformation(TZI)
    LocalTime = GMT - TimeSerial(0, TZI.Bias, 0) + _
            IIf(DST = TIME_ZONE_DAYLIGHT, TimeSerial(1, 0, 0), 0)
    GetLocalTimeFromGMT = LocalTime
End Function

Function SystemTimeToVBTime(SysTime As SYSTEMTIME) As Date
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' SystemTimeToVBTime
' This converts a SYSTEMTIME structure to a VB/VBA date value.
' It assumes SysTime is valid -- no error checking is done.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    With SysTime
        SystemTimeToVBTime = DateSerial(.wYear, .wMonth, .wDay) + _
                TimeSerial(.wHour, .wMinute, .wSecond)
    End With
End Function

Function LocalOffsetFromGMT(Optional AsHours As Boolean = False, _
    Optional AdjustForDST As Boolean = False) As Long
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' LocalOffsetFromGMT
' This returns the amount of time in minutes (if AsHours is omitted or
' false) or hours (if AsHours is True) that should be added to the
' local time to get GMT. If AdjustForDST is missing or false,
' the unmodified difference is returned. (e.g., Kansas City to London
' is 6 hours normally, 5 hours during DST. If AdjustForDST is False,
' the resultif 6 hours. If AdjustForDST is True, the result is 5 hours
' if DST is in effect.)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim TBias As Long
    Dim TZI As TIME_ZONE_INFORMATION
    Dim DST As TIME_ZONE
    DST = GetTimeZoneInformation(TZI)

    If DST = TIME_ZONE_DAYLIGHT Then
        If AdjustForDST = True Then
            TBias = TZI.Bias + TZI.DaylightBias
        Else
            TBias = TZI.Bias
        End If
    Else
        TBias = TZI.Bias
    End If
    If AsHours = True Then
        TBias = TBias / 60
    End If

    LocalOffsetFromGMT = TBias
End Function

Function DaylightTime() As TIME_ZONE
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' DaylightTime
' Returns a value indicating whether the current date is
' in Daylight Time, Standard Time, or that Windows cannot
' deterimine the time status. The result is a member or
' the TIME_ZONE enum.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim TZI As TIME_ZONE_INFORMATION
    Dim DST As TIME_ZONE
    DST = GetTimeZoneInformation(TZI)
    DaylightTime = DST
End Function
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 VBA (Excel) 中获取时区信息 的相关文章

随机推荐

  • 使用动态 WHERE 语句创建 SQL 查询

    我使用 Postgresql 作为我的数据库 以防万一这有帮助 尽管我想找到一种纯 SQL 方法而不是 Postgresql 特定的实现 我有大量从制造电子产品中获得的测试数据 我想获取该组数据并从中提取哪些单元在测试期间满足某些标准 最好
  • 如何在 play /scala 的控制器类中发送表单元素数据

    my routes conf POST getVerticalIndustry1 guid controllers Application getVerticalIndustry guid 我的 html javascript partyI
  • javax.el.E​​LException:未找到提供程序 com.sun.el.E​​xpressionFactoryImpl

    尽管有很多问题解决方案 但我仍然坚持这个问题ELException org springframework beans factory BeanCreationException Error creating bean with name
  • 如何在Nuxt的asyncData方法中获取用户的IP?

    Nuxt 使用 asyncData 在服务器端运行代码 然后将其与数据对象合并 我想拨打一个需要我知道用户IP的电话 我看到我可以到达req object https nuxtjs org api context 确实有但它被埋了深 深 h
  • LNK2019:错误。使用 InternetOpen InternetReadFIle 的 C++ 程序中无法解析的外部符号

    我尝试编写一个简单的程序来从网站获取信息 我无法编译 因为我收到 InternetReadFile InternetOpenUrl 等的 LNK2019 错误 例如 1 gt GetInternetInfo obj 错误LNK2019 无法
  • 如何提高数据插入/更新性能?

    我需要提高数据加载的性能 当前的算法从表中进行完整选择 select Field1 Field2 FieldN from Table1 order by FieldM 新数据是从文本文件中读取的 例如 每个数据表行的文本文件行 该表有一个主
  • 如何通过 Puppeteer 获取元素的子元素

    我明白那个puppeteer拥有自己的手柄而不是标准手柄DOM元素 但我不明白为什么我不能通过找到的元素继续相同的查询 const els await page div parent for let i 0 i lt els length
  • Android模拟器SDCard因某种原因被删除

    我在 AVD 中创建了一个 3 2 使用 Google API 设备 但是 我最近似乎无法使用 SDCard 在使用时 Environment getExternalStorageState 我收到 已删除 如何重新安装 撤消删除 SD 卡
  • 使用 aws-cli 创建 api-gateway lambda 集成

    我需要使用 aws 客户端创建一个 api 网关 我使用 Web 控制台成功创建并集成了我的 aws lambda 函数 但我对 aws client 感到困惑 这些是我遵循的步骤 创建 api 网关并使用 Web 控制台与我的示例 lam
  • 如何用笑话模拟猫鼬链接查询

    在测试套件上我想用链接方法模拟模型findOne then select 登录服务 public loggingIn async loginDTO LoginDTO gt const user await UserModel findOne
  • Visual Studio 团队服务部署/构建证书错误

    我正在尝试使用 VSTS Visual studio 团队在线服务 中的持续集成和部署功能构建一个单击一次应用程序我们正在尝试使用托管代理 Visual studio 2015 构建此应用程序我们在使用强名称密钥文件签名时遇到了困难的错误
  • ORA-00060: 等待资源时检测到死锁

    我有一系列脚本作为 nohup 在托管 Oracle 10g 的 AIX 服务器上并行运行 这些脚本是由其他人编写的 旨在同时执行 所有脚本都在表上执行更新 我收到错误 ORA 00060 检测到死锁 等待资源 当我用谷歌搜索这个时 我发现
  • 如何插入包含页码、文件路径和图像的页脚?

    I m trying to format the footer so it has the page x out of y on the top right of the footer and then the image centered
  • 使用 Velocity 和 Jasmine 测试 Meteor 时需要超时

    对于流星 速度和茉莉花来说还很陌生 所以不确定我是否做错了什么 使用茉莉花来做它不适合的事情 或者这只是它的工作方式 我发现我需要为几乎所有测试设置超时才能让它们通过 应该是这种情况还是我做错了什么 例如 我正在运行一些测试来检查验证消息
  • 当列表项很少时,如何将页脚视图显示到屏幕末尾?

    我想向列表视图添加页脚 当列表项数量较多时 页脚效果很好 但是当列表视图的项目很少时 页脚会显示在屏幕中间 就在列表视图的下方 这看起来很破旧 在这种情况下 我希望页脚与父底部对齐 谢谢你的期待 这是你想要的最简单的例子 你可以自定义它
  • cocos2d中忽略精灵的透明区域

    我已经被困了好几个星期了 现在试图找出如何忽略对精灵透明区域的触摸 我一直在尝试使用本教程来跟踪像素完美碰撞 http www learn cocos2d com 2011 12 fast pixelperfect collision de
  • Python 单元测试 - 如何修补我正在测试的方法内部的异步调用

    我使用 unittest mock 为我的 python 代码构建测试 我有一个正在尝试测试的方法 其中包含对另一个函数的异步调用 我想修补该异步调用 以便我可以让 Mock 返回一个测试值asset id 而不是实际调用异步方法 我尝试了
  • std::memory_order_seq_cst 的工作原理

    我从以下位置获取了有关 std memory order seq cst 的示例 http en cppreference com w cpp atomic memory order http en cppreference com w c
  • HTML 输入换行文本而不是水平溢出

    我有一个input字段 用户将在其中输入文本 当文本变得太长时 输入字段会水平延伸 而不是垂直下降 我尝试添加这个CSS overflow hidden word wrap break word 但我没有运气 关于如何实现这一目标还有其他建
  • 在 VBA (Excel) 中获取时区信息

    我想在 VBA 中确定不同国家 地区在特定日期的 GMT UTC 时间偏移 包括夏令时 有任何想法吗 编辑 来自自我回答 谢谢 0xA3 我快速浏览了链接页面 我假设您只能获取 Windows 运行所在本地的 GMT 偏移量 Convert