Lean  $LEAN_TAG$
DoubleUnixSecondsDateTimeJsonConverter.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using Newtonsoft.Json;
18 
19 namespace QuantConnect.Util
20 {
21  /// <summary>
22  /// Defines a <see cref="JsonConverter"/> that serializes <see cref="DateTime"/> use the number of whole and fractional seconds since unix epoch
23  /// </summary>
25  {
26  private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
27 
28  /// <summary>
29  /// Determines whether this instance can convert the specified object type.
30  /// </summary>
31  /// <param name="objectType">Type of the object.</param>
32  /// <returns>
33  /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
34  /// </returns>
35  public override bool CanConvert(Type objectType)
36  {
37  return objectType == typeof(DateTime)
38  || objectType == typeof(DateTime?);
39  }
40 
41  /// <summary>
42  /// Convert the input value to a value to be serialzied
43  /// </summary>
44  /// <param name="value">The input value to be converted before serialziation</param>
45  /// <returns>A new instance of TResult that is to be serialzied</returns>
46  protected override double? Convert(DateTime? value)
47  {
48  if (value == null)
49  {
50  return null;
51  }
52 
53  return (value.Value - UnixEpoch).TotalSeconds;
54  }
55 
56  /// <summary>
57  /// Converts the input value to be deserialized
58  /// </summary>
59  /// <param name="value">The deserialized value that needs to be converted to T</param>
60  /// <returns>The converted value</returns>
61  protected override DateTime? Convert(double? value)
62  {
63  if (value == null)
64  {
65  return null;
66  }
67 
68  return UnixEpoch.AddSeconds(value.Value);
69  }
70  }
71 }