转换UTC / GMT时间,本地时间 [英] Convert UTC/GMT time to local time

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

问题描述

我们正在开发一个C#应用程序的Web服务客户端。这将运行在Windows XP的PC。

We are developing a C# application for a web-service client. This will run on Windows XP PC's.

一个由Web服务返回的字段是一个日期时间字段。服务器返回GMT形式即场以Z结尾。

One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end.

然而,我们发现,.NET似乎做某种类型的隐式转换和时间固定为12小时取出。

However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out.

下面code样本解析这在12个小时的时差已经在一定程度上,但它使新西兰夏令时没有考虑。

The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving.

CultureInfo ci = new CultureInfo("en-NZ");
string date = "Web service date".ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            

根据此日期网站

UTC / GMT偏移

UTC/GMT Offset

标准时区:UTC / GMT12小时
  夏令时:1小时
  目前时区偏移: UTC / GMT13小时

Standard time zone: UTC/GMT +12 hours
Daylight saving time: +1 hour
Current time zone offset: UTC/GMT +13 hours

我们如何调整额外小时?可以这样做编程,或这是某种形式在PC上的?

How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?

推荐答案

对于字符串,如 2012-09-19 01:27:30.000 DateTime.Parse 看不出来哪个时区的日期和时间距离。

For strings such as 2012-09-19 01:27:30.000, DateTime.Parse cannot tell what time zone the date and time are from.

的DateTime 拥有的的属性,它可以有三个时区选项之一:

DateTime has a Kind property, which can have one of three time zone options:

  • 未指定
  • 本地
  • UTC

注意 如果您希望重新present之外的日期/时间不是UTC或本地时区,那么你应该使用<一个href="http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx"><$c$c>DateTimeOffset.

因此​​,对于code在你的问题:

So for the code in your question:

DateTime convertedDate = DateTime.Parse(dateStr);

var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified

你说你知道这是什么样的,所以告诉它。

You say you know what kind it is, so tell it.

DateTime convertedDate = DateTime.SpecifyKind(
    DateTime.Parse(dateStr),
    DateTimeKind.Utc);

var kind = convertedDate.Kind; // will equal DateTimeKind.Utc

现在,一旦系统知道它在UTC时间,你可以叫 ToLocalTime

Now, once the system knows its in UTC time, you can just call ToLocalTime:

DateTime dt = convertedDate.ToLocalTime();

这会给你你需要的结果。

This will give you the result you require.

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

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