我们正在为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);根据此日期网站:
UTC / GMT偏移
标准时区:UTC / GMT +12小时 夏令时:+1小时 当前时区偏移量: UTC / GMT +13小时
我们如何调整额外的小时?这可以通过编程方式完成,还是PC上的这种设置?
解决方案对于诸如 2012-09-19 01:27:30.000 , DateTime.Parse 无法确定日期和时间是从哪个时区。 >
DateTime 有一个种属性,可以有三个时区选项之一:
- 未指定
- 本地
- Utc
注意 如果您希望代表UTC或本地时区之外的日期/时间,那么您应使用 DateTimeOffset 。
所以对于你的问题的代码:
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:
UTC/GMT Offset
Standard time zone: UTC/GMT +12 hours Daylight saving time: +1 hour Current time zone offset: UTC/GMT +13 hours
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.UnspecifiedYou 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.UtcNow, 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时间转换为当地时间
发布评论