GPAL - Generally Positive Automation Library v1.0
GPAL The Fluent Automation LIbrary
Loading...
Searching...
No Matches
DateTimeOffsetYamlConverter.cs
1// =============================================================================
2// GPAL - Generally Positive Automation Library
3// Copyright © 2026 Software Decisions, Inc. All rights reserved.
4//
5// This file is part of GPAL.
6// Licensed under the Business Source License 1.1
7//
8// Primary development, architecture, and vision by Michael B. Vederman,
9// CEO of Software Decisions, Inc., Texas.
10//
11// Internal development maintained privately.
12// Public releases appear on GitHub: https://github.com/SoftwareDecisionsInc/GPAL.
13//
14// See LICENSE for full terms, including Additional Use Grant.
15// =============================================================================
16
17using System;
18using System.Globalization;
19using YamlDotNet.Core;
20using YamlDotNet.Core.Events;
21using YamlDotNet.Serialization;
22
29public class DateTimeOffsetYamlConverter : IYamlTypeConverter
30{
31 public bool Accepts(Type type)
32 {
33 return type == typeof(DateTimeOffset) || typeof(DateTimeOffset?) == type;
34 }
35
36 public object ReadYaml(IParser parser, Type type)
37 {
38 var scalar = parser.Consume<Scalar>();
39
40 if (string.IsNullOrEmpty(scalar.Value) || scalar.Value.ToLower() == "null")
41 return null;
42
43 return DateTimeOffset.Parse(scalar.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
44 }
45
46 public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
47 {
48 var scalarValue = rootDeserializer(typeof(string)) as string;
49
50 if (string.IsNullOrEmpty(scalarValue) || scalarValue.ToLower() == "null")
51 return null;
52
53 return DateTimeOffset.Parse(scalarValue, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
54 }
55
56 public void WriteYaml(IEmitter emitter, object value, Type type)
57 {
58 if (value == null)
59 emitter.Emit(new Scalar("null"));
60 else
61 emitter.Emit(new Scalar(null, null, ((DateTimeOffset)value).ToString("o", CultureInfo.InvariantCulture)));
62 }
63
64 public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer)
65 {
66 if (value == null)
67 emitter.Emit(new Scalar("null"));
68 else
69 serializer(((DateTimeOffset)value).ToString("o", CultureInfo.InvariantCulture), typeof(string));
70 }
71}
Writes a DateTimeOffset as a single round-trippable string, and a null as a null. Without this YamlDo...