简体   繁体   English

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

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

I'm converting the UTC time, taken from my local Server time to Central standard time. 我正在将UTC时间从本地服务器时间转换为中央标准时间。 I have this running on a server in Germany. 我已经在德国的服务器上运行了这个程序。

Converting the time and date works, but when a library i have converts it to a string it has a wrong Timezone offset. 转换时间和日期是可行的,但是当我将库转换为字符串时,它具有错误的时区偏移量。

It comes out as 2019-05-11T14:44:09+02:00 when i need it to be 2019-05-11T14:44:09-06:00 当我需要它成为2019-05-11T14:44:09-06:00时,它显示为2019-05-11T14:44:09 + 02:00

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

The +02:00 is the UTCoffset for Germany, which i don't want, even the the time and date are correctly in Central Time. +02:00是德国的UTC偏移量,我不希望这样做,即使时间和日期都正确地位于中部时间。

Is there a way to pass or include the offset in the DateTime object? 有没有办法在DateTime对象中传递或包含偏移量?

Is there a way to pass or include the offset in the DateTime object? 有没有办法在DateTime对象中传递或包含偏移量?

No, DateTime structure does not have UTC Offset but DateTimeOffset has. 不, DateTime结构没有 UTC偏移 ,但DateTimeOffset了。 If you really wanna keep your UTC Offset value in your code, I suggest you to work with DateTimeOffset instead of DateTime . 如果您确实想在代码中保留UTC偏移值,建议您使用DateTimeOffset而不是DateTime

Since it doesn't keep UTC Offset value, when you get it's textual (aka string) representation, you still get the offset value of your server in Germany (includes K , z , zz and zzz specifiers by the way). 由于它不保留UTC偏移值,因此,当获得文本 (aka字符串)表示形式时,您仍将获得德国服务器的偏移值(顺便说一下,包括Kzzzzzz说明符)。 TimeZoneInfo.ConvertTimeFromUtc method returns a DateTime instance, the offset value you might wanna represent depends on how you want to show it. TimeZoneInfo.ConvertTimeFromUtc方法返回一个DateTime例如,您可能想表示偏移值取决于你想如何表达。

One option might be that you might wanna concatenate The Sortable ("s") Format Specifier representation of your DateTime and your TimeZoneInfo.BaseUtcOffset value. 一种选择是,您可能想要串联DateTime和TimeZoneInfo.BaseUtcOffset的Sortable(“ s”)Format Specifier表示形式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM