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

web服务返回的字段之一是DateTime字段。服务器返回一个GMT格式的字段,即结尾有一个“Z”。

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

下面的代码示例在一定程度上解决了这个问题,因为12小时的差异已经消失,但它不考虑新西兰的夏令时。

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

根据这个约会网站:

UTC / GMT抵消 标准时区:UTC/GMT +12小时 夏令时:+1小时 当前时区偏移:UTC/GMT +13小时

我们如何调整额外的一小时?这可以通过编程来完成吗?或者这是PC上的某种设置吗?


当前回答

我有一个问题,它是在一个数据集被推到电线(网络服务到客户端),它会自动改变,因为DataColumn的DateType字段被设置为本地。确保你在推数据集时检查DateType是什么。

如果不希望更改,则将其设置为Unspecified

其他回答

TimeZone.CurrentTimeZone.ToLocalTime(date);

我遇到了这个问题,因为我有一个UTC日期的问题,你通过twitter API (created_at字段的状态);我需要将它们转换为DateTime。本页上的答案/代码示例中的答案都不足以阻止我得到“字符串不被识别为有效的DateTime”错误(但这是我在SO上找到正确答案的最接近的答案)

在这里发布这个链接,以防这有助于其他人-我需要的答案在这篇博客文章中找到:http://www.wduffy.co.uk/blog/parsing-dates-when-aspnets-datetimeparse-doesnt-work/ -基本上使用DateTime。ParseExact使用格式字符串代替DateTime。解析

对于Dana的建议:

代码示例现在看起来像:

string date = "Web service date"..ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);

原定日期是2008年8月20日;就是UTC。

convertedDate和dt都是一样的:

21/08/08 10:00:26;这种是本地的

我会考虑使用这套系统。TimeZoneInfo类,如果你在。net 3.5。见http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx。这应该正确地考虑到夏时制的变化。

// Coordinated Universal Time string from 
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z"; 
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date); 
DateTime utcDateTime = localDateTime.ToUniversalTime();

// ID from: 
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);

我有一个问题,它是在一个数据集被推到电线(网络服务到客户端),它会自动改变,因为DataColumn的DateType字段被设置为本地。确保你在推数据集时检查DateType是什么。

如果不希望更改,则将其设置为Unspecified