Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An implementation of JSON converter between Unix's timestamp in milliseconds and .NET's DateTime for Json.NET
public class UnixMillisDateTimeConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
var dateTime = (DateTime)value;
var offset = new DateTimeOffset(dateTime);
var unixTimestamp = offset.ToUnixTimeMilliseconds();
writer.WriteValue(unixTimestamp);
}
public override object ReadJson(JsonReader reader, Type type, object value, JsonSerializer serializer)
{
if (reader.Value == null)
{
return type == typeof(DateTime?) ? (object)null : DateTime.MinValue;
}
long epoch;
if (reader.ValueType == typeof(long))
{
epoch = (long)reader.Value;
}
else
{
epoch = long.Parse((string)reader.Value);
}
var offset = DateTimeOffset.FromUnixTimeMilliseconds(epoch);
return offset.DateTime;
}
public override bool CanConvert(Type type)
{
return type == typeof(DateTime) || type == typeof(DateTime?);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.