服务客户端日期时间时区偏移兼容性问题

时间:2011-03-21 16:32:24

标签: .net datetime service wcf-client

我正在尝试使用Visual Studio服务引用(System.ServiceModel命名空间类)通过.NET应用程序与Java Web服务进行通信。我发现只要序列化DateTime值,它就不会指定偏移量。问题有两个:

  1. 我无法弄清楚如何使用特定时区创建DateTime对象。我可以创建一个DateTimeOffset来完成此任务,但服务客户端需要一个DateTime对象。
  2. 当序列化DateTime对象时,它不包括时区偏移量。
  3. 要详细说明问题#2,服务期望的timestamp对象的XML如下:

      <startDate>2011-03-18T00:00:00-07:00</startDate>
      <endDate>2011-03-19T00:00:00-07:00</endDate>
    

    但是,我在跟踪.NET应用程序时看到的XML如下:

      <startDate>2011-03-18T00:00:00</startDate>
      <endDate>2011-03-19T00:00:00</endDate>
    

    Web服务需要时区,因为基础数据是以GMT-0跟踪的。返回的数据是每日间隔,因此如果我没有指定时区,那么我将获取GMT-0的数据。只有当我在查询中提供偏移量时才能获得数据正确的时区。

1 个答案:

答案 0 :(得分:1)

建议:将所有DateTimeOffset值转换为UTC中的DateTime值,并将它们提交给webapp。

static DateTime ConvertFromDateTimeOffset(DateTimeOffset dateTime) {
   if (dateTime.Offset.Equals(TimeSpan.Zero))
      return dateTime.UtcDateTime;
   else if (dateTime.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(dateTime.DateTime)))
      return DateTime.SpecifyKind(dateTime.DateTime, DateTimeKind.Local);
   else
      return dateTime.DateTime;
}

从此页面:A General-Purpose Conversion Method

希望这有助于。