我们向我们的客户公开了一个WCF网络服务,允许他们在SQL Server数据库中存储DateTime。WSDL的摘录:
<xs:complexType name="TimePeriod">
<xs:sequence>
<xs:element minOccurs="0" name="endDateTime" nillable="true" type="xs:dateTime"/>
<xs:element minOccurs="0" name="startDateTime" nillable="true" type="xs:dateTime"/>
</xs:sequence>
例如,我的客户向我发送UTC日期时间:
<af:effectivePeriod>
<af:startDateTime>2018-01-16T10:32:28Z</af:startDateTime>
</af:effectivePeriod>
它存储在SQL Server数据库的datetime
字段中。
但是在读取服务的输出中,我没有UTC指示器:
<af:effectivePeriod>
<af:startDateTime>2018-01-16T10:32:28</af:startDateTime>
</af:effectivePeriod>
"Z“是DateTimes的一种独特情况。文字"Z“实际上是UTC时间的ISO8601DateTime标准的一部分。当"Z“(Zulu)被附加在时间的末尾时,它表示该时间是UTC,所以字面上的Z实际上是时间的一部分
我怎么可能在read方法的输出端获得Z
?我是否必须修改存储在SQL Server中的数据类型?我对服务的WSDL有影响吗?
发布于 2018-07-05 06:44:13
微软有一个在将日期和时间与字符串相互转换时如何“往返”的explanation;而你的问题(我将在下面讨论)是你丢失了Kind
。
DateTime
ToString
方法的"o“standard format将为您提供您正在寻找的”往返“类型。
使用RoundTripKind
的DateTime
Parse() with DateTimeStyles读取值。
您的DateTime
缺少'Z‘指示符这一事实意味着(如“o”的“标准格式”页中所述)DateTime
的Kind
为Unspecified
。如果您已从数据库中读取这些DateTime
,则Kind
将为Unspecified
(您可以在读取Kind
属性后使用调试器对其进行检查以确认这一点)。
解决这个问题的方法是,您必须知道您存储的是哪种类型的DateTime
,因此您可以在读取它时设置它的类型(因为如果您不这样做,类型将是未指定的)。例如,如果您只存储UTC
Kind
DateTime
,那么当您从数据库中读取它们时,您可以在DateTime上适当地设置Kind
。你可以这样做:
var myUtcDateTime = DateTime.SpecifyKind(myUnspecifiedDateTime, DateTimeKind.Utc);
我有一个扩展方法来封装它,所以我可以简单地调用:
var myDateTime = dataReader.GetUtcDateTime(ordinal);
它是这样实现的:
public static class DataReaderExtensions
{
public static DateTime GetUtcDateTime(this IDataReader reader, int ordinal)
{
var readDateTime = reader.GetDateTime(ordinal);
return DateTime.SpecifyKind(readDateTime, DateTimeKind.Utc);
}
}
或者,您可以查看this answer以了解如何使用实体框架来完成此任务。
(请注意,这种方法适用于UTC;但您不能决定对某种Local
__执行相同的操作,因为不能保证读取值的本地位置与写入该值的位置相同。例如,夏令时可能刚刚开始或结束。)
但是我不得不说,如果你真的对实际时间感兴趣,解决这类问题的更好的解决方案(如果你原谅我的双关语!)是使用DateTimeOffset
,它们存储DateTime和偏移量,并保证你得到你输入的东西,而不需要修修补补。
发布于 2018-07-02 18:56:13
在您的WCF数据契约中,您可以添加一个DateTimeOffset DataMember,但是它将对客户端产生影响,并且您的服务wsdl将随着复杂类型DateTimeOffset的创建而更改:
<xs:complexType name="DateTimeOffset">
<xs:annotation>
<xs:appinfo>
<IsValueType>true</IsValueType>
</xs:appinfo>
</xs:annotation>
<xs:sequence>
<xs:element name="DateTime" type="xs:dateTime"/>
<xs:element name="OffsetMinutes" type="xs:short"/>
</xs:sequence>
</xs:complexType>
https://stackoverflow.com/questions/51133778
复制相似问题