首页 > 解决方案 > 根据机器本地设置,将带有时区的日期时间解析为 DateTimeOffset 的行为会有所不同

问题描述

使用此日期调用 api:

2021-01-09T21:13:00 +00:00

或者

2021-01-09T21:13:00 +01:00

我将此日期转换为根据机器的本地设置以不同方式转换的 api,是否可以隔离此行为并始终在 UTC 时区获取日期?

public class Movimento
    {
        public int Id { get; set; }
        [JsonConverter(typeof(ExperimentalConverter))]
        public DateTimeOffset MyDate { get; set; }
        .......

}



public class ExperimentalConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTimeOffset) || objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        /*
                =============IF MY MACHINE LOCAL TIME IS SET TO UTC + 01:00  ========================
                i got "09/01/2021 21:13:00" -->  when the client call the api passing --> "2021-01-09T21:13:00+01:00"
                i got "09/01/2021 22:13:00" -->  when the client call the api passing --> "2021-01-09T21:13:00+00:00"

                 =============IF MY MACHINE LOCAL TIME IS SET TO UTC (UTC +  00:00)  ========================
                i got "09/01/2021 20:13:00" -->  when the client call the api passing --> "2021-01-09T21:13:00+01:00"
                i got "09/01/2021 21:13:00" -->  when the client call the api passing --> "2021-01-09T21:13:00+00:00"
         */
        var parsedData = (DateTime)reader.Value;   // 09/01/2021 21:13:00  when the api pass "2021-01-09T21:13:00+01:00"

        //i need a way to uderstad if the received date is in UTC format or UTC+01:00 indipendently from the local settings of the machine, so i can later riapply the offset i need 
        //"parsedData.Kind" give me always the value Local (because the date in this method is already translates according to the local settings of the machine 
        
        .......
    }

标签: c#json.nettimezoneutcdatetimeoffset

解决方案


通常,当您解析 a 时DateTimeOffset,将保留偏移量。但不幸的是,当您将 aJsonConverter应用于DateTimeOffset属性时,reader.Value遗嘱(使用默认设置)包含 aDateTime偏移量已经受到计算机本地时区的影响。

要解决此问题,DateParseHandling.DateTimeOffset请在序列化设置中进行设置。

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    DateParseHandling = DateParseHandling.DateTimeOffset
};

然后reader.Value将包含一个DateTimeOffset,您可以将其拆箱。

此外,您可以使用它JsonConverter<T>来简化代码,并且不需要处理DateTime解析(除非您的问题中没有描述其他要求)。

public class UtcDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
{
    public override DateTimeOffset ReadJson(JsonReader reader, Type objectType, DateTimeOffset existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        // First get the DateTimeOffset exactly as presented (asserting never-null)
        var value = (DateTimeOffset) reader.Value!;

        // Then convert it to UTC before returning it.
        return value.ToUniversalTime();
    }

    public override void WriteJson(JsonWriter writer, DateTimeOffset value, JsonSerializer serializer)
    {
        // Convert the value to UTC and write it to JSON using a Z suffix
        writer.WriteValue(value.UtcDateTime);      
    }
}

我还为您提供了一个WriteJson对这类事情有意义的实现,在输出 JSON 中使用 aZ而不是。+00:00

这里的工作示例。


推荐阅读