C# 中的 Utcoffset 格式
Utcoffset formats in C#
var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
Console.WriteLine(((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));
以上代码运行良好。但我需要显示 +05:00 之类的偏移量。有什么办法可以实现这种格式吗?
而不是使用 TimeZone
从 DateTime.Now
查找时区,您可以使用 DateTimeOffset.Now
与 zzz
格式字符串和 CultureInfo.InvariantCulture
来实现这个:
Console.WriteLine(DateTimeOffset.Now.ToString("HHmmzzz", System.Globalization.CultureInfo.InvariantCulture));
// outputs 1255+02:00
如果您只想要该格式的偏移量,可以使用 "zzz"
而不是 "HHmmzzzz"
。
来自docs:
The custom TimeSpan format specifiers don't include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals.
所以你必须转义你的格式字符串中没有在上面页面中列出的字符,或者用 '
包围它,或者用反斜杠,所以:
utcOffset.ToString("hh':'mm")
但是,如果您格式化 DateTimeOffset
而不是 TimeSpan
,您实际上不必自己进行此格式化。如果这样做,您也不需要所有“获取 UTC 偏移量”的麻烦。
你只需要 zzz Custom Format Specifier:
DateTimeOffset.Now.ToString("zzz")
您不需要所有 TimeZone
东西。
var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
Console.WriteLine(((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));
以上代码运行良好。但我需要显示 +05:00 之类的偏移量。有什么办法可以实现这种格式吗?
而不是使用 TimeZone
从 DateTime.Now
查找时区,您可以使用 DateTimeOffset.Now
与 zzz
格式字符串和 CultureInfo.InvariantCulture
来实现这个:
Console.WriteLine(DateTimeOffset.Now.ToString("HHmmzzz", System.Globalization.CultureInfo.InvariantCulture));
// outputs 1255+02:00
如果您只想要该格式的偏移量,可以使用 "zzz"
而不是 "HHmmzzzz"
。
来自docs:
The custom TimeSpan format specifiers don't include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals.
所以你必须转义你的格式字符串中没有在上面页面中列出的字符,或者用 '
包围它,或者用反斜杠,所以:
utcOffset.ToString("hh':'mm")
但是,如果您格式化 DateTimeOffset
而不是 TimeSpan
,您实际上不必自己进行此格式化。如果这样做,您也不需要所有“获取 UTC 偏移量”的麻烦。
你只需要 zzz Custom Format Specifier:
DateTimeOffset.Now.ToString("zzz")
您不需要所有 TimeZone
东西。