1

I send an request from client to the server. My client is in Melbourne (+10) and the server is located in Germany (+1). When I send a Datetime (11.06.2018 00:00:00+10:00) it parses to German time (10.06.2018 16:00:00+01). The code where the parse happens is this one:

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();
}

The DateTimeZoneHandler from the reader is RoundTripKind.

How can I prevent the parsing so the datetime stays like 11.06.2018 00:00:00+10?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Maybe you could do something like in this SO post? https://stackoverflow.com/questions/3188933/prevent-timezone-conversion-on-deserialization-of-datetime-value – Freggar Jun 11 '18 at 07:42

1 Answers1

1

DateTime store a date and time value, and also a .Kind, which can be DateTimeKind.Local, DateTimeKind.Utc, or DateTimeKind.Unspecified. It cannot store an arbitrary offset.

Conversely, DateTimeOffset stores a date and time value, and also an offset from UTC.

Thus, if you want to retain the same offset you received, you should not use a DateTime type, but rather use a DateTimeOffset instead. It is made for that purpose.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • First of all thanks for the response :) But I'm sorry, I normally code in javascript so I'm pretty unsure in c# things.. How do I code that? The JSON object from the request looks like {..., 'ActivityDate': '2018-06-13T00:00:00+13:00',...}. So in the JSONReader the time is still like that, but if I read it with the JToken Reader it parses to "ActivityDate: 2018-06-12T13:00:00+02:00" Again... Sorry for my stupidity – Marvin Rügheimer Jun 13 '18 at 07:18
  • You probably don't need to work at this low level at all, but it's hard to say because your example isn't complete. TBH, I'm not sure why you're boxing everything as an `object` in the first place. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Thanks. – Matt Johnson-Pint Jun 13 '18 at 18:52