I need to convert UTC
date strings to DateTimeOffsets
.
This must work with a timezone which differs from the computers timezone. E.g. current computer timezone is +02:00, but I want to create a DateTimeOffset with offset -4:00.
I already read lot of questions here on stackoverflow, but none of them solved my problem.
That is what I need to do:
Input: "2012-11-20T00:00:00Z"
Output: DateTimeOffset with:
Of course daylight saving must be taken into account.
edit: To make things even clearer, please try to complete the following code snippet:
DateTimeOffset result; const string dateString = "2012-11-20T00:00:00Z"; var timezone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"); //this timezone has an offset of +01:00:00 on this date //do conversion here Assert.AreEqual(result.Offset, new TimeSpan(1, 0, 0)); //the correct utc offset, in this case +01:00:00 Assert.AreEqual(result.UtcDateTime, new DateTime(2012, 11, 20, 0, 0, 0)); //equals the original date Assert.AreEqual(result.LocalDateTime, new DateTime(2012, 11, 20, 1, 0, 0));
The main difference between it and the simpler DateTime type we all know and love is that it includes a time zone offset from UTC. Thus, it's always clear when looking at a DateTimeOffset what time is meant, whether UTC or local.
Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).
With its Kind property, DateTime is able to reflect only Coordinated Universal Time (UTC) and the system's local time zone. DateTimeOffset reflects a time's offset from UTC, but it does not reflect the actual time zone to which that offset belongs.
In performing the conversion to local time, the method first converts the current DateTimeOffset object's date and time to Coordinated Universal Time (UTC) by subtracting the offset from the time. It then converts the UTC date and time to local time by adding the local time zone offset.
Here is the solution you are looking for:
const string dateString = "2012-11-20T00:00:00Z"; TimeZoneInfo timezone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"); //this timezone has an offset of +01:00:00 on this date DateTimeOffset utc = DateTimeOffset.Parse(dateString); DateTimeOffset result = TimeZoneInfo.ConvertTime(utc, timezone); Assert.AreEqual(result.Offset, new TimeSpan(1, 0, 0)); //the correct utc offset, in this case +01:00:00 Assert.AreEqual(result.UtcDateTime, new DateTime(2012, 11, 20, 0, 0, 0)); //equals the original date Assert.AreEqual(result.DateTime, new DateTime(2012, 11, 20, 1, 0, 0));
Note that you were incorrectly testing the .LocalDateTime
property - which is always going to convert the result to the local time zone of the computer. You simply need the .DateTime
property instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With