8

If I have a DateTime instance which represents a valid UTC time, and an offset that converts that DateTime to the time zone where it applies, how do I construct a DateTimeOffset instance to represent this?

var utcDateTime = new DateTime(2011, 02, 29, 12, 43, 0, /*DateTimeKind.Utc*/);
var localOffset = TimeSpan.FromHours(2.0);

var dto = ...

// Here the properties should be as follows;
// dto.UtcDateTime = 2011-02-29 12:43:00
// dto.LocalDateTime = 2011-02-29 14:43:00

Perhaps I'm not understanding the DateTimeOffset structure correctly, but I'm unable to get the expected output.

Thanks in advance

0

1 Answer 1

17

Looks like you want:

var utcDateTime = new DateTime(2012, 02, 29, 12, 43, 0, DateTimeKind.Utc);
var dto = new DateTimeOffset(utcDateTime).ToOffset(TimeSpan.FromHours(2));

Note that I changed the year from 2011 (which is not a leap year and does not have 29 days in February) to 2012.

Test:

Console.WriteLine("Utc = {0}, Original = {1}", dto.UtcDateTime, dto.DateTime);

Output:

Utc = 2/29/2012 12:43:00 PM, Original = 2/29/2012 2:43:00 PM

Do note that you probably don't want the LocalDateTime property, which may represent the instant in time as of the local system's timezone.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that's perfect. So the DateTimeOffset(DateTime, TimeSpan) constructor expects a non-UTC date. It was LocalDateTime that threw me - using the DateTime property makes more sense! ... Also, 2011 was a typo :P Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.