Reputation: 1336
I'm converting the UTC time, taken from my local Server time to Central standard time. 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
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.
Is there a way to pass or include the offset in the DateTime object?
Upvotes: 1
Views: 2624
Reputation: 98848
Is there a way to pass or include the offset in the DateTime object?
No, DateTime
structure does not have UTC Offset but DateTimeOffset
has. If you really wanna keep your UTC Offset value in your code, I suggest you to work with DateTimeOffset
instead of 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). TimeZoneInfo.ConvertTimeFromUtc
method returns a DateTime
instance, the offset value you might wanna represent depends on how you want to show it.
One option might be that you might wanna concatenate The Sortable ("s") Format Specifier representation of your DateTime and your TimeZoneInfo.BaseUtcOffset
value.
TimeZoneInfo CRtimezone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
$"{TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, CRtimezone).ToString("s")}{CRtimezone.BaseUtcOffset}".Dump();
Upvotes: 4