简体   繁体   中英

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. 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.

session.StartTime.ToString(CultureInfo.InvariantCulture)

Yaml generated:

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

637209323680070971 - On the original

637209323680000000 - On the deserialized one:

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.

If you need the milliseconds, you can use the roundtrip format , "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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