【发布时间】:2021-04-26 23:09:19
【问题描述】:
使用此日期调用 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到DateTime的转换似乎总是使用未指定的DateTimeKind,这使得它最终格式化为本地。如果阅读器将该值存储为DateTimeOffset,那么您应该将其转换为该值,然后使用UtcDateTime属性将其保持为UTC(如果您正在尝试这样做)。DateTime/DateTimeOffset这些年来的选角行为让我很头疼。 -
@MartinCostello
(DateTimeOffset)reader.Value给我错误,所以我尝试DateTimeOffset.Parse(reader.Value.ToString());这样是不是时区丢失了? -
对于
Parse(),您应该使用采用DateTimeStyles值的重载。然后您可以控制时区的处理方式(例如DateTimeStyles.AdjustToUniversal):docs.microsoft.com/en-us/dotnet/api/…
标签: c# json.net timezone utc datetimeoffset