我的 json 中有一个日期时间,格式如下:
“事件日期”:“2017-05-05T11:35:44-07:00”,
此文件是在太平洋时间创建的,而我的服务器是东部时间。当我将此文件反序列化回我的对象时,时间将转换为日期时间 2017-05-05 2:35:44PM。问题是我需要原始时间 11:35:44AM。
我已经从源头上解决了问题,但我仍然需要一种方法来处理我拥有的所有这些文件。有没有办法将此字段反序列化为指定的确切日期时间而不带偏移量?我检查了 DateTimeZoneHandling 设置,但没有一个产生我想要的效果。
最佳答案
我同意上面评论中的 AWinkle - 最好的方法是反序列化为 DateTimeOffset 而不是 DateTime - 这样,您就可以根据需要显示它。
也就是说,我将这个想法用于一种可能的方法,即使用自定义 JSON 类型转换器来获取您想要的时区剥离行为。这是我敲出的一个快速示例,它似乎按照您的要求进行。
/// <summary>
/// Custom converter for returning a DateTime which has been stripped of any time zone information
/// </summary>
public class TimezonelessDateTimeConverter : DateTimeConverterBase {
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException("An exercise for the reader...");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
// We'll make use of Json.NET's own IsoDateTimeConverter so
// we don't have to re-implement everything ourselves.
var isoConverter = new IsoDateTimeConverter();
// Deserialise into a DateTimeOffset which will hold the
// time and the timezone from the JSON.
var withTz = (DateTimeOffset)isoConverter.ReadJson(reader, typeof(DateTimeOffset), existingValue, serializer);
// Return the DateTime component. This will be the original
// datetime WITHOUT timezone information.
return withTz.DateTime;
}
}
然后可以像这样使用:
/// <summary>
/// Nonsense class just to represent your data. You'd implement the JsonConverter
/// attribute on your own model class.
/// </summary>
public class Sample {
[JsonConverter(typeof(TimezonelessDateTimeConverter))]
public DateTime EventDate { get; set; }
}
//
// And a sample of the actual deserialisation...
///
var json = "{ \"EventDate\": \"2017-05-05T11:35:44-07:00\" }";
var settings = new JsonSerializerSettings {
DateParseHandling = DateParseHandling.DateTimeOffset
};
var deserialised = JsonConvert.DeserializeObject<Sample>(json, settings);
Console.WriteLine(deserialised.EventDate);
这将输出 05/05/2017 11:35:44
。
这绝对不是最可靠的方法,我几乎可以肯定有些事情我没有考虑到 - 并且它可能应该进行更彻底的测试,以确保没有一些可怕的副作用。不过,希望这是一个可能的解决方案的起点,并为您指明正确的方向。
附注如果您还序列化回 JSON,则还需要实现 WriteJson 方法。我没有这样做,所以现在它只有一个方向。
关于c# - 反序列化日期时间时忽略时区偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44166565/