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

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

问题描述

我们正在为 Web 服务客户端开发 C# 应用程序.这将在 Windows XP PC 上运行.

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

Web 服务返回的字段之一是 DateTime 字段.服务器返回 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.

以下代码示例在一定程度上解决了这个问题,因为 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/GMT +12 小时
夏令时:+1 小时
当前时区偏移:UTC/GMT +13 小时

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 有一个 Kind 属性,它可以有三个时区选项之一:

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

  • 未指定
  • 本地
  • UTC

注意 如果您希望表示 UTC 或本地时区以外的日期/时间,则应使用 DateTimeOffset.

对于您问题中的代码:

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天全站免登陆