MasstransferExporter/MasstransferCommon/Convert/DatetimeConverter.cs

25 lines
888 B
C#
Raw Normal View History

using Newtonsoft.Json;
using JsonSerializer = Newtonsoft.Json.JsonSerializer;
namespace MasstransferCommon.Convert;
public class DatetimeConverter : JsonConverter<DateTime>
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
{
long timestamp = (long)(value.ToUniversalTime() - UnixEpoch).TotalMilliseconds;
writer.WriteValue(timestamp);
}
public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
var value = reader.Value;
return long.TryParse(value + "", out var timestamp)
? UnixEpoch.AddMilliseconds(timestamp)
: UnixEpoch.AddMilliseconds((long)value);
}
}