我们正在为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上的某种设置吗?


当前回答

我会考虑使用这套系统。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

@TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)

对于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;这种是本地的

不要忘记,如果你已经有一个DateTime对象,并且不确定它是UTC还是Local,直接使用对象上的方法是很容易的:

DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();

我们如何调整额外的一小时?

除非指定。net将使用本地pc设置。我会读到:http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx

从外观上看,代码可能是这样的:

DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );

如上所述,仔细检查您的服务器设置的时区。网上有关于如何安全地影响IIS中的更改的文章。

该代码块使用通用时间转换当前DateTime对象,然后将其转换回本地DateTime。对我来说是完美的,我希望它能帮助到你!

CreatedDate.ToUniversalTime().ToLocalTime();