Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

c# - Convert UTC DateTime to DateTimeOffset

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:

  • UtcDateTime of 2012-11-20 00:00
  • the correct Utc offset for the defined timezone (01:00 in this example)
  • LocalDateTime: 2012-11-20 01:00 (= UtcDateTime + Offset)

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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...