Last active
June 21, 2017 01:19
-
-
Save lindexi/9a5bc7cd455add6ab87f81270dbf9768 to your computer and use it in GitHub Desktop.
json unix timestamp to dateTime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UnixConvert : JsonConverter | |
{ | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
var time = ToUnixTimestamp((DateTime) value); | |
writer.WriteValue(time); | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
long unixTimeStamp = long.Parse(reader.Value.ToString()); | |
return UnixTimeStampToDateTime(unixTimeStamp); | |
} | |
public override bool CanConvert(Type objectType) | |
{ | |
return true; | |
} | |
private static DateTime UnixTimeStampToDateTime(long unixTimeStamp) | |
{ | |
System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); | |
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp); | |
return dtDateTime; | |
} | |
public static long ToUnixTimestamp(DateTime time) | |
{ | |
var date = new DateTime(1970, 1, 1, 0, 0, 0, time.Kind); | |
var unixTimestamp = System.Convert.ToInt64((time - date).TotalSeconds); | |
return unixTimestamp; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment