将UTC日期时间转换为DateTimeOffset [英] Convert UTC DateTime to DateTimeOffset

查看:389
本文介绍了将UTC日期时间转换为DateTimeOffset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to convert UTC date strings to DateTimeOffsets.

此时间段必须与计算机时区不同。
例如当前计算机时区为+02:00,但我想创建一个偏移量为-4:00的DateTimeOffset。

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.

我已经在stackoverflow上阅读了很多问题,但没有他们中的人解决了我的问题。

I already read lot of questions here on stackoverflow, but none of them solved my problem.

这就是我需要做的:

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

Input: "2012-11-20T00:00:00Z"

输出: DateTimeOffset,其中:

Output: DateTimeOffset with:


  • UtcDateTime of 2012-11-20 00:00

  • 已定义时区的正确Utc偏移量(在此示例中为01:00)

  • LocalDateTime: 2012-11-20 01:00 (= UtcDateTime +偏移量)

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

当然必须考虑夏令时。

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

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


推荐答案

这是您要寻找的解决方案:

Here is the solution you are looking for:

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

请注意,您错误地测试了 .LocalDateTime 属性-始终会将结果转换为计算机的本地时区。您只需要 .DateTime 属性即可。

Note that you were incorrectly testing the .LocalDateTime property - which is always going to convert the result to the local timezone of the computer. You simply need the .DateTime property instead.

这篇关于将UTC日期时间转换为DateTimeOffset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆