首页 > 解决方案 > Datetime Arrives to Server Converted to UTC

问题描述

We are running .NET Core 2.1 on Linux. We do a POST with body below, and it seems for all 3 cases the datetime is converted to UTC time, instead of keeping the local time with offset as submitted. What is surprising is that even JSON properties deserialized to string are still showing converted value.

We are trying to retain the local value for further processing.

JSON:

{
    "ts": "2020-09-27T01:23:27.047-04:00",
    "tsTest": "2020-09-27T01:23:27.047-04:00",
    "tsTest2": "2020-09-27T01:23:27.047-04:00"
}

Model:

public class HealthAssessmentResponseDto
    {
        [JsonProperty("ts")]
        // public string LocalDttmStr { get; set; }
        public DateTimeOffset LocalDttm { get; set; }

        [JsonProperty("tsTest")]
        public string LocalDttmStr { get; set; }

        [JsonProperty("tsTest2")]
        [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-ddTHH:mm:ssK")]
        public DateTimeOffset LocalDttmConverted { get; set; }
    }

    public class DateFormatConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
    {
        public DateFormatConverter(string format)
        {
            DateTimeFormat = format;
        }
    }

Result

{
    "tranId": "7be8989c-c310-4b7a-a5a2-1706398f94f8",
    "payload": {
        "rto": true,
        "message": "LocalDttmStr: 2020-09-27T05:23:27, LocalDttmConverted: 09/27/2020 05:23:27 +00:00, DatetimeOffset: 09/27/2020 05:23:27 +00:00"
    }
}

标签: c#jsondatetime

解决方案


推荐阅读