c# - 反序列化日期时间时忽略时区偏移

标签 c# json datetime json.net

我的 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/

相关文章:

c# - 可以生成 Excel 报告并将其推送到客户端计算机,而无需将文件保存在服务器中

javascript - 采用表单字段名称和值创建 JSON 架构

javascript - 带有 JSON 数据源的 C3.js 流 api 不起作用

json - json 数据源可以保存/包含图像吗?

java - java - 如何从当前日期减少一个月并使用java存储在日期变量中?

java - 从scala中的字符串计算日期

c# - 如何将类型不变的 setter 添加到协变接口(interface)?

c# - Parallel.ForEach仅在未运行代码时才在启动时执行两次吗?

.net - 如何使用 FluentValidation 将字符串验证为 DateTime

c# - ASP.NET 核心在单例服务上调用异步初始化