Skip to content

Instantly share code, notes, and snippets.

@ismaelhamed
Last active January 2, 2016 12:48
Show Gist options
  • Save ismaelhamed/f61936ee664c282e737e to your computer and use it in GitHub Desktop.
Save ismaelhamed/f61936ee664c282e737e to your computer and use it in GitHub Desktop.
*NIX Epoch integer converter for DateTime
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class UnixDateTimeConverter : DateTimeConverterBase
{
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Integer)
throw new Exception(string.Format("Unexpected token parsing date. Expected Integer, got {0}.", reader.TokenType));
var unixTime = (long)reader.Value;
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unixTime);
return epoch;
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var dateTime = ((DateTime)value).ToUniversalTime().Subtract(epoch);
var unixTime = (long)Math.Floor(dateTime.TotalSeconds);
writer.WriteValue(unixTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment