反序列化datetime时忽略时区偏移量

时间:2017-05-24 19:01:10

标签: c# json datetime json.net

我的json中的日期时间格式如下:

“EventDate”:“2017-05-05T11:35:44-07:00”,

此文件是在太平洋时间创建的,而我的服务器是在东部时间。当我将此文件反序列化回我的对象​​时,时间将转换为2017-05-05的下午2:35:44 PM。问题是我需要原始时间,上午11:35:44。

我已经在源头修复了问题,但我仍然需要一种方法来处理我拥有的所有这些文件。有没有办法将此字段反序列化为没有偏移量的指定的确切日期时间?我检查了DateTimeZoneHandling设置,但没有一个产生我想要的效果。

1 个答案:

答案 0 :(得分:1)

我同意上面评论中的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

这绝对不是最强大的方法,我几乎可以肯定有些事情我没有考虑到 - 而且可能应该进行更彻底的测试,以确保不存在一些可怕的副作用。但是,希望它是一个可能的解决方案的起点,并指出你正确的方向。

P.S。如果您还要序列化回JSON,那么您也需要实现WriteJson方法。我没有那样做,所以现在它只朝一个方向发展。