c# – 将UTC DateTime转换为DateTimeOffset

我需要将UTC日期字符串转换为DateTimeOffsets.

这与时区不同,它与计算机时区不同.
例如.当前计算机时区为02:00,但是我想创建一个偏移-4:00的DateTimeOffset.

我已经在stackoverflow上看了很多问题,但是他们都没有解决我的问题.

这就是我需要做的:

输入:“2012-11-20T00:00:00Z”

输出:DateTimeOffset:

> 2012-11-20 00:00的UtcDateTime
>定义的时区的正确Utc偏移量(本例中为01:00)
> LocalDateTime:2012-11-20 01:00(= UtcDateTime Offset)

当然,必须考虑到夏令时.

编辑:
为了使事情更加清晰,请尝试完成以下代码段:

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));
以下是您要查找的解决方案:

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

var utc = DateTimeOffset.Parse(dateString);
var offset = timezone.GetUtcOffset(utc);
var result = utc.ToOffset(offset);

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));

请注意,您不正确地测试.LocalDateTime属性 – 它总是将结果转换为计算机的本地时区.您只需要.DateTime属性.

翻译自:https://stackoverflow.com/questions/13933654/convert-utc-datetime-to-datetimeoffset

转载注明原文:c# – 将UTC DateTime转换为DateTimeOffset