-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathUnixMilliDateTimeConverter.cs
45 lines (34 loc) · 1.79 KB
/
UnixMilliDateTimeConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PriceInsight;
[JsonConverter(typeof(UnixMilliDateTimeConverter))]
public record UnixMilliDateTime(DateTime Value) {
[return: NotNullIfNotNull(nameof(self))]
public static implicit operator DateTime?(UnixMilliDateTime? self) => self?.Value;
}
public class UnixMilliDateTimeConverter : JsonConverter<UnixMilliDateTime> {
public override bool HandleNull => false;
public override UnixMilliDateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
if (reader.TryGetInt64(out var time)) {
return new UnixMilliDateTime(DateTimeOffset.FromUnixTimeMilliseconds(time).LocalDateTime);
}
throw new JsonException("Expected date object value.");
}
public override void Write(Utf8JsonWriter writer, UnixMilliDateTime value, JsonSerializerOptions options) => throw new NotSupportedException();
}
[JsonConverter(typeof(UnixSecondDateTimeConverter))]
public record UnixSecondDateTime(DateTime Value) {
public static implicit operator DateTime?(UnixSecondDateTime? self) => self?.Value;
}
public class UnixSecondDateTimeConverter : JsonConverter<UnixSecondDateTime> {
public override bool HandleNull => false;
public override UnixSecondDateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
if (reader.TryGetInt64(out var time)) {
return new UnixSecondDateTime(DateTimeOffset.FromUnixTimeSeconds(time).LocalDateTime);
}
throw new JsonException("Expected date object value.");
}
public override void Write(Utf8JsonWriter writer, UnixSecondDateTime value, JsonSerializerOptions options) => throw new NotSupportedException();
}