GMT时间转换为当地时间

GMT时间转换为当地时间

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

问题描述

限时删除!!

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



Web服务返回的一个字段是DateTime字段。服务器返回一个格式为格式的字段,最后是Z。



然而,我们发现.NET似乎做了某种隐式转换,时间总是12个小时。



以下代码示例在一定程度上解决了12小时差异,但不允许新西兰夏令时。 / p>

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

根据:

我们如何调整额外的小时?这可以通过编程方式完成,还是PC上的这种设置?

解决方案

对于诸如 2012-09-19 01:27:30.000 DateTime.Parse 无法确定日期和时间是从哪个时区。 >

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


  • 未指定

  • 本地

  • Utc



注意 如果您希望代表UTC或本地时区之外的日期/时间,那么您应使用。






所以对于你的问题的代码:

  DateTime convertedDate = DateTime.Parse(dateStr); 

var kind = convertedDate.Kind; //将等于DateTimeKind.Unspecified

你说你知道这是什么,所以告诉它。 / p>

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

var kind = convertedDate.Kind; //将等于DateTimeKind.Utc

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

  DateTime dt = convertedDate.ToLocalTime(); 

这将为您提供所需的结果。


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

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.

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

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

As per this date site:

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

解决方案

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 has a Kind property, which can have one of three time zone options:

  • Unspecified
  • Local
  • Utc

NOTE If you are wishing to represent a date/time other than UTC or your local time zone, then you should use DateTimeOffset.


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

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时间转换为当地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:34