2 using System.Globalization;
4 using Newtonsoft.Json.Converters;
5 using Newtonsoft.Json.Utilities;
7 namespace Pithos.Interfaces
10 /// Converts a <see cref="DateTime"/> to and from a JavaScript date constructor (e.g. new Date(52231943)).
12 public class PithosDateTimeConverter : DateTimeConverterBase
14 private DateTime _epoch = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc);
17 /// Writes the JSON representation of the object.
19 /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
20 /// <param name="value">The value.</param>
21 /// <param name="serializer">The calling serializer.</param>
22 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
26 if (value is DateTime)
28 var dateTime = (DateTime)value;
29 var utcDateTime = dateTime.ToUniversalTime();
30 seconds = (utcDateTime - _epoch).TotalSeconds; ;
32 else if (value is DateTimeOffset)
34 var dateTimeOffset = (DateTimeOffset)value;
35 var utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
36 seconds= (utcDateTimeOffset.UtcDateTime - _epoch).TotalSeconds;
40 throw new Exception("Expected date object value.");
43 writer.WriteValue(seconds);
47 /// Reads the JSON representation of the object.
49 /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
50 /// <param name="objectType">Type of the object.</param>
51 /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
52 /// <param name="serializer">The calling serializer.</param>
53 /// <returns>The object value.</returns>
54 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
56 Type t = (IsNullableType(objectType))
57 ? Nullable.GetUnderlyingType(objectType)
60 if (reader.TokenType == JsonToken.Null)
62 if (!IsNullableType(objectType))
63 throw new Exception(String.Format("Cannot convert null value to {0}.",objectType));
68 var seconds = double.Parse((string)reader.Value,CultureInfo.InvariantCulture);
70 DateTime d = _epoch.AddSeconds(seconds);
73 if (t == typeof(DateTimeOffset))
74 return new DateTimeOffset(d);
78 public static bool IsNullableType(Type t)
81 throw new ArgumentNullException("t");
83 return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));