4

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

4

1 回答 1

11

看起来你想要:

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

请注意,我将年份从 2011 年(不是闰年,二月没有 29 天)更改为 2012 年。

测试:

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

输出:

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

请注意,您可能想要该LocalDateTime属性,它可能代表本地系统时区的即时时间。

于 2012-02-29T12:58:43.343 回答