将 .Net TimeZoneInfo 转换为 POSIX 时区 [已关闭]

问题描述 投票:0回答:2

我需要将 .Net 中的时区转换为 POSIX 时区。我可以通过

TimeZoneInfo
GetAdjustmentRules
获取夏令时开始、结束和增量,但是我仍然会缺少时区缩写代码(例如 MST/MDT、PST/PDT 等)。在 C# .Net 中执行此操作。

本质上,我正在寻找的与此相反:Convert a posix style timezone to timezoneinfo in c# .net

对于这样的事情有现有的解决方案吗?或者有人知道我可以在哪里获得标准时间和夏令时缩写代码吗?

编辑:我刚刚收到一条消息,该问题已关闭,因为有人将其误解为寻求建议而不是问题的解决方案。我不知道关闭它的人是如何得出这个结论的,但没有询问任何建议。

c# .net timezone posix
2个回答
0
投票

我刚刚添加了对 POSIX 时区字符串的支持,作为我的 TimeZoneConverter 项目的附加组件。它位于一个名为

TimeZoneConverter.Posix
的单独包中。安装它,您可以执行以下操作:

string posix = PosixTimeZone.FromTimeZoneInfo(SomeTimeZoneInfoObject);

此外,您只需提供 Windows 时区 ID 或 IANA 时区名称,这也可以:

string posix = PosixTimeZone.FromWindowsTimeZoneId("Eastern Standard Time");
// Result: "EST5EDT,M3.2.0,M11.1.0"

string posix = PosixTimeZone.FromIanaTimeZoneName("Australia/Sydney");
// Result: "AEST-10AEDT,M10.1.0,M4.1.0/3"

请记住,您仍然受到 POSIX 时区的限制:

  • 他们每年只能支持两次转换。
  • 并非所有时区转换都适用于 DST。有些是针对标准时间的更改,但此处未反映出来。它们看起来像 DST 过渡。
  • 他们不为自己提供任何历史变化。

最后一点,上面显示的示例使用 current 年份,但也有重载来提供年份以生成特定于该年份的字符串。


0
投票

我参加这个聚会迟到了,但我在查看微软是否已经实施了任何东西时发现了这篇文章。如果 .NET TimeZoneInfo 类有一个方法可以实现这一点,那就太好了。 许多年前,我写了一些东西来将 .NET TimeZoneInfo 对象转换为 posix 时区字符串。它并不完美——获取时区名称缩写并不容易,而且 posix 不支持复杂的时区。但请查看旧的 C# 代码,您可以在这里找到:

https://muman.ch/pub/PosixTimeZones.cs

它有这些有用的方法:

    /// <summary>
    /// Returns the posix time zone string for a .NET TimeZoneInfo object.
    /// </summary>
    /// <param name="tzi"></param>
    /// <returns></returns>
    public static string GetPosixTZString(TimeZoneInfo tzi);


    /// <summary>
    /// Validates a posix time zone string.
    /// See https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
    /// and https://data.iana.org/time-zones/theory.html
    // 
    // stdzone [ dstzone [, rule [, rule] ] ]
    //
    // zone :=  name offset
    // name :=  3 or more characters, any except ":,+-0123456789<>"
    //          |=  <[+|-]nn>, e.g. "<+05>" (quoted form - not supported by QNX?)
    // offset   :=  [+|-]hh[:mm[:ss]]
    // rule     :=  Mm.n.d[/time], e.g. "M3.1.0/2"
    // m        :=  1..12
    // n        :=  1..5
    // d        :=  0..6, or 1..31
    // time     :=  hh[:mm[:ss]], leading + or - not allowed
    // 
    /// </summary>
    /// <param name="posixTz"></param>
    /// <returns></returns>
    public static bool IsValidPosixTZString(string posixTz);
© www.soinside.com 2019 - 2024. All rights reserved.