问题描述
使用此日期调用 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
.......
}
解决方法
通常,当您解析 DateTimeOffset
时,偏移量将被保留。但不幸的是,当您将 JsonConverter
应用于 DateTimeOffset
属性时,reader.Value
将(使用默认设置)包含一个 DateTime
,其中偏移量已经受到计算机的影响当地时区。
要解决此问题,请在序列化设置中设置 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 中使用 Z
而不是 +00:00
。