c# 将 UTC 时间转换为中央时间,包括 DateTime 对象中的时区

c# Converting UTC time to Central including timezone in DateTime object

我正在将 UTC 时间从我的本地服务器时间转换为中央标准时间。我在德国的服务器上有这个 运行。

转换时间和日期有效,但是当我将其转换为字符串时,它的时区偏移量有误。

结果为 2019-05-11T14:44:09+02:00 当我需要它时 2019-05-11T14:44:09-06:00

TimeZoneInfo CRtimezone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, CRtimezone);

+02:00 是德国的 UTCoffset,我不想要它,即使时间和日期在中部时间是正确的。

有没有办法在 DateTime 对象中传递或包含偏移量?

Is there a way to pass or include the offset in the DateTime object?

没有,DateTime结构有没有UTC Offset but DateTimeOffset有。如果您真的想在代码中保留 UTC 偏移值,我建议您使用 DateTimeOffset 而不是 DateTime

因为它不保留 UTC 偏移值,当你得到它的文本(又名字符串)表示时,你仍然得到您在德国的服务器的偏移值(顺便说一下,包括 Kzzzzzz 说明符)。 TimeZoneInfo.ConvertTimeFromUtc 方法 returns 一个 DateTime 实例,您可能想要表示的偏移值取决于 如何 您想要显示它。

一个选项可能是您想要连接 The Sortable ("s") Format Specifier representation of your DateTime and your TimeZoneInfo.BaseUtcOffset 值。

TimeZoneInfo CRtimezone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
$"{TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, CRtimezone).ToString("s")}{CRtimezone.BaseUtcOffset}".Dump();