diff --git a/src/NATS.Client.Core/INatsSerialize.cs b/src/NATS.Client.Core/INatsSerialize.cs index 82f815a9e..3b4819d06 100644 --- a/src/NATS.Client.Core/INatsSerialize.cs +++ b/src/NATS.Client.Core/INatsSerialize.cs @@ -116,7 +116,7 @@ public void Serialize(IBufferWriter bufferWriter, T value) { if (value is DateTime input) { - if (Utf8Formatter.TryFormat(input, span, out var written)) + if (Utf8Formatter.TryFormat(input, span, out var written, new StandardFormat('O'))) { bufferWriter.Advance(written); } @@ -133,7 +133,19 @@ public void Serialize(IBufferWriter bufferWriter, T value) { if (value is DateTimeOffset input) { - if (Utf8Formatter.TryFormat(input, span, out var written)) + bool result; + int written; + if (input.Offset == TimeSpan.Zero) + { + // This will make it place `Z` instead of `+00:00` at the end + result = Utf8Formatter.TryFormat(input.UtcDateTime, span, out written, new StandardFormat('O')); + } + else + { + result = Utf8Formatter.TryFormat(input, span, out written, new StandardFormat('O')); + } + + if (result) { bufferWriter.Advance(written); } @@ -392,7 +404,7 @@ public void Serialize(IBufferWriter bufferWriter, T value) if (buffer.Length == 0) return default; - if (Utf8Parser.TryParse(span, out DateTime value, out _)) + if (Utf8Parser.TryParse(span, out DateTime value, out _, 'O')) { return (T)(object)value; } @@ -405,7 +417,7 @@ public void Serialize(IBufferWriter bufferWriter, T value) if (buffer.Length == 0) return default; - if (Utf8Parser.TryParse(span, out DateTimeOffset value, out _)) + if (Utf8Parser.TryParse(span, out DateTimeOffset value, out _, 'O')) { return (T)(object)value; } diff --git a/tests/NATS.Client.Core2.Tests/SerializerTest.cs b/tests/NATS.Client.Core2.Tests/SerializerTest.cs index eabc317df..f63c7a746 100644 --- a/tests/NATS.Client.Core2.Tests/SerializerTest.cs +++ b/tests/NATS.Client.Core2.Tests/SerializerTest.cs @@ -68,8 +68,9 @@ public async Task NatsMemoryOwner_empty_payload_should_not_throw() public void Utf8_serializer() { SerializeDeserialize("foo", "foo"); - SerializeDeserialize(DateTime.MinValue, "01/01/0001 00:00:00"); - SerializeDeserialize(DateTimeOffset.MinValue, "01/01/0001 00:00:00 +00:00"); + SerializeDeserialize(new DateTime(1970, 12, 31, 23, 42, 2, DateTimeKind.Utc), "1970-12-31T23:42:02.0000000Z"); + SerializeDeserialize(new DateTimeOffset(1970, 12, 31, 23, 42, 2, TimeSpan.Zero), "1970-12-31T23:42:02.0000000Z"); + SerializeDeserialize(new DateTimeOffset(1970, 12, 31, 23, 42, 2, TimeSpan.FromHours(1)), "1970-12-31T23:42:02.0000000+01:00"); SerializeDeserialize(Guid.Empty, "00000000-0000-0000-0000-000000000000"); SerializeDeserialize(TimeSpan.Zero, "00:00:00"); SerializeDeserialize(true, "True");