简体   繁体   English

c# 如何使用 YamlDotNet 序列化 DateTime 以便它可以反序列化?

[英]c# How to serialize DateTime using YamlDotNet so that it can be deserialized?

In .net Framework 4.8, am trying to serialize via YamlDotNet an object that contains a DateTime field, usually created via a DateTime.Now call.在 .net Framework 4.8 中,我试图通过YamlDotNet序列化一个包含DateTime字段的对象,该字段通常通过DateTime.Now调用创建。 I use a custom serializer for that object, seralizing with the following as the key's value.我为该对象使用自定义序列化程序,将以下内容作为键值进行序列化。 This produces a valid yaml, witch i can deserialize.这会产生一个有效的 yaml,我可以反序列化。

session.StartTime.ToString(CultureInfo.InvariantCulture)

Yaml generated: Yaml 生成:

StartTime: 03/27/2020 18:59:27

When deserializing i get a DateTime Object with the same year, month, day, hour and second, but the ticks seem to different反序列化时,我得到一个具有相同年、月、日、小时和秒的DateTime对象,但刻度似乎不同

637209323680070971 - On the original 637209323680070971 - 在原件上

637209323680000000 - On the deserialized one: 637209323680000000 - 在反序列化的一个:

How can i serialize/deserialize it so the 2 objects are the same?我如何序列化/反序列化它以便两个对象相同?

I don't need the accuracy the extra ticks provide, but got no clue on how to remove them or what is the proper way of solving this error我不需要额外刻度提供的准确性,但不知道如何删除它们或解决此错误的正确方法是什么

If you don't care about the milliseconds, you don't need to do anything, as the value being parsed is equal to what you have written in the YAML.如果您不关心毫秒,则无需执行任何操作,因为解析的值等于您在 YAML 中编写的值。

If you need the milliseconds, you can use the roundtrip format , "o" :如果需要毫秒,可以使用往返格式"o"

session.StartTime.ToString("o", CultureInfo.InvariantCulture)

By default, YamlDotNet will use the Convert.ChangeType to parse dates, and that method accepts that format among others.默认情况下,YamlDotNet 将使用Convert.ChangeType来解析日期,并且该方法接受该格式等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM