在为 PST 配置的计算机上给定一个 Local DateTime 值(当 DST 开始时,它将在 3 月 10 日隐式更改为 PDT),如何获得包含适当 时区的字符串 - 例如。 PST/PDT,不抵消! - 在输出中?
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ???")
预期的输出字符串,例如:
"2019-02-09 13:04:22 PST" // right after lunch today
"2019-04-09 13:04:22 PDT" // right after lunch in two months
MSDN DateTime Custom Format Strings页面显示了将“PST”明确硬编码到输出中的示例,这将在半年和/或本地 TZ 更改时出错。计算机和人会移动,因此硬编码 TZ 值根本“不合适”。
最好这可以通过只是一个格式字符串来完成,允许在呈现/到字符串阶段之前提供日期时间值——尽管似乎没有“ZZZ”格式。我已经指定了“本地”日期时间类型,希望能减少一些额外的怪癖。
最佳答案
由于 DateTime
实例不保留时区信息,因此无法使用自定义日期和时间格式字符串来实现。 "zzz"
specifier用于 UTC Offset值,DateTime.Kind
与 "K"
specifier也不反射(reflect)时区缩写。两者对您的情况都没有用。
但是,有一个名为 TimeZoneNames 的 nuget 包这是时区极客写的Matt Johnson您可以获得时区名称的缩写(同时支持 IANA 和 Windows 时区标识符)
var tz = TZNames.GetAbbreviationsForTimeZone("Pacific Standard Time", "en-US");
Console.WriteLine(tz.Standard); // PST
Console.WriteLine(tz.Daylight); // PDT
如果您想以编程方式获取 Windows 时区标识符,可以使用 TimeZoneInfo.Local.Id
property , 如果你想得到当前的语言代码,你可以使用 CultureInfo.CurrentCulture.Name
property顺便说一下。
var tz = TZNames.GetAbbreviationsForTimeZone(TimeZoneInfo.Local.Id, CultureInfo.CurrentCulture.Name);
但在此之前,您应该检查您的本地时间是否为夏令时,以选择要附加您的格式化字符串的缩写。
DateTime now = DateTime.Now;
bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(now);
如果 isDaylight
为 true
,您应该使用 TimeZoneValues.Daylight
属性的结果,否则您应该使用 TimeZoneValues。第一个代码部分的标准
属性。
最后,您需要在 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss)
字符串的末尾附加其中一个缩写。
Matt 在包裹页面上的重要说明;
Time zone abbreviations are sometimes inconsistent, and are not necessarily localized correctly for every time zone. In most cases, you should use abbreviations for end-user display output only. Do not attempt to use abbreviations when parsing input.
来自 Matt's comment 的第二条重要说明;
What makes you think that a time zone abbreviation actually exists for every time zone and every language in the world? Even, then what makes you think that a time zone abbreviation is enough to identify the time zone? Hint - both questions are amorphous. Consider "CST" or "IST" - Each have three or four places in the world that they might belong to. Many many many other cases as well...
关于c# - 根据一年中的时间使用适当的本地 DST 感知时区(例如 PST 或 PDT)格式化本地 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610867/