C# 从客户端时间到服务器时间解析JSON字符串中的DateTime
我从客户端向服务器发送请求。我的客户端位于墨尔本(+10),服务器位于德国(+1)。当我发送日期时间(11.06.2018 00:00:00+10:00)时,它解析为德国时间(10.06.2018 16:00:00+01)。 进行解析的代码如下所示:C# 从客户端时间到服务器时间解析JSON字符串中的DateTime,c#,.net,json,parsing,datetime,C#,.net,Json,Parsing,Datetime,我从客户端向服务器发送请求。我的客户端位于墨尔本(+10),服务器位于德国(+1)。当我发送日期时间(11.06.2018 00:00:00+10:00)时,它解析为德国时间(10.06.2018 16:00:00+01)。 进行解析的代码如下所示: public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { v
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var data = new List<object>();
// DateTime is correct in JsonReader reader but wrong in JToken dataArray
JToken dataArray = JToken.ReadFrom(reader); //parses in this line
if (!dataArray.HasValues) return null;
foreach (JToken dataItem in dataArray)
{
if (dataItem is JValue)
{
object value = (dataItem as JValue).Value;
data.Add(value == null ? value : value.ToString());
}
else
{
data.Add(dataItem);
}
}
return data.ToArray();
}
public override object ReadJson(JsonReader reader,类型objectType,对象existingValue,JsonSerializer序列化程序)
{
var data=新列表();
//DateTime在JsonReader中是正确的,但在JToken dataArray中是错误的
JToken dataArray=JToken.ReadFrom(reader);//在此行中解析
如果(!dataArray.HasValues)返回null;
foreach(数据数组中的JToken数据项)
{
if(数据项为JValue)
{
对象值=(数据项为JValue);
data.Add(value==null?value:value.ToString());
}
其他的
{
data.Add(数据项);
}
}
返回data.ToArray();
}
读者提供的DateTimeZoneHandler是RoundTripKind
如何防止解析,使datetime保持为2018年6月11日00:00:00+10?
datetime
存储日期和时间值,以及.Kind
,可以是DateTimeKind.Local
,DateTimeKind.Utc
或DateTimeKind.Unspecified
。它不能存储任意偏移量
相反,DateTimeOffset
存储日期和时间值,以及与UTC的偏移量
因此,如果希望保留收到的相同偏移量,则不应使用
DateTime
类型,而应使用DateTimeOffset
。它就是为了这个目的而制作的。也许你可以在这篇文章中做类似的事情?首先感谢您的回复:)但很抱歉,我通常用javascript编写代码,所以我对c#东西很不确定。。我该如何编写代码?请求中的JSON对象看起来像{…,'ActivityDate':'2018-06-13T00:00:00+13:00',…}。所以在JSONReader中时间仍然是这样的,但是如果我用JToken阅读器阅读它,它会再次解析为“ActivityDate:2018-06-12T13:00:00+02:00”。。。对不起,我的愚蠢你可能根本不需要在这么低的层次上工作,但很难说,因为你的例子不完整。TBH,我不知道你为什么一开始就把所有东西都当作对象来装箱。请阅读。谢谢