UnixDateTimeConverter
Converts a DateTime to and from Unix epoch time
using Newtonsoft.Json.Utilities;
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace Newtonsoft.Json.Converters
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class UnixDateTimeConverter : DateTimeConverterBase
{
internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public bool AllowPreEpoch { get; set; }
public UnixDateTimeConverter()
: this(false)
{
}
public UnixDateTimeConverter(bool allowPreEpoch)
{
AllowPreEpoch = allowPreEpoch;
}
public override void WriteJson(JsonWriter writer, [System.Runtime.CompilerServices.Nullable(2)] object value, JsonSerializer serializer)
{
TimeSpan timeSpan;
long num;
if (value is DateTime) {
timeSpan = ((DateTime)value).ToUniversalTime() - UnixEpoch;
num = (long)timeSpan.TotalSeconds;
} else {
if (!(value is DateTimeOffset))
throw new JsonSerializationException("Expected date object value.");
timeSpan = ((DateTimeOffset)value).ToUniversalTime() - (DateTimeOffset)UnixEpoch;
num = (long)timeSpan.TotalSeconds;
}
if (!AllowPreEpoch && num < 0)
throw new JsonSerializationException("Cannot convert date value that is before Unix epoch of 00:00:00 UTC on 1 January 1970.");
writer.WriteValue(num);
}
[return: System.Runtime.CompilerServices.Nullable(2)]
public override object ReadJson(JsonReader reader, Type objectType, [System.Runtime.CompilerServices.Nullable(2)] object existingValue, JsonSerializer serializer)
{
bool flag = ReflectionUtils.IsNullable(objectType);
if (reader.TokenType == JsonToken.Null) {
if (!flag)
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null;
}
long result;
if (reader.TokenType == JsonToken.Integer)
result = (long)reader.Value;
else {
if (reader.TokenType != JsonToken.String)
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer or String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
if (!long.TryParse((string)reader.Value, out result))
throw JsonSerializationException.Create(reader, "Cannot convert invalid value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
if (AllowPreEpoch || result >= 0) {
DateTime dateTime = UnixEpoch.AddSeconds((double)result);
if ((flag ? Nullable.GetUnderlyingType(objectType) : objectType) == typeof(DateTimeOffset))
return new DateTimeOffset(dateTime, TimeSpan.Zero);
return dateTime;
}
throw JsonSerializationException.Create(reader, "Cannot convert value that is before Unix epoch of 00:00:00 UTC on 1 January 1970 to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
}
}