Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json\Converters\IsoDateTimeConverter.cs

Symbol Coverage: 95.56% (43 of 45)

Branch Coverage: 92.50% (37 of 40)

Cyclomatic Complexity Avg: 3.11 Max:10

Code Lines: 43


L V Source
1
using System;
2
using System.Globalization;
3
using Newtonsoft.Json.Utilities;
4

  
5
namespace Newtonsoft.Json.Converters
6
{
7
  /// <summary>
8
  /// Converts a <see cref="DateTime"/> to and from the ISO 8601 date format (e.g. 2008-04-12T12:53Z).
9
  /// </summary>
10
  public class IsoDateTimeConverter : DateTimeConverterBase
11
  {
12
    private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
13

  
14
 38
    private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
15
    private string _dateTimeFormat;
16
    private CultureInfo _culture;
17

  
18
    /// <summary>
19
    /// Gets or sets the date time styles used when converting a date to and from JSON.
20
    /// </summary>
21
    /// <value>The date time styles used when converting a date to and from JSON.</value>
22
    public DateTimeStyles DateTimeStyles
23
    {
24
 2
      get { return _dateTimeStyles; }
25
 12
      set { _dateTimeStyles = value; }
26
    }
27

  
28
    /// <summary>
29
    /// Gets or sets the date time format used when converting a date to and from JSON.
30
    /// </summary>
31
    /// <value>The date time format used when converting a date to and from JSON.</value>
32
    public string DateTimeFormat
33
    {
34
 2
      get { return _dateTimeFormat ?? string.Empty; }
35
 4
      set { _dateTimeFormat = StringUtils.NullEmptyString(value); }
36
    }
37

  
38
    /// <summary>
39
    /// Gets or sets the culture used when converting a date to and from JSON.
40
    /// </summary>
41
    /// <value>The culture used when converting a date to and from JSON.</value>
42
    public CultureInfo Culture
43
    {
44
 75
      get { return _culture ?? CultureInfo.CurrentCulture; }
45
 5
      set { _culture = value; }
46
    }
47

  
48
    /// <summary>
49
    /// Writes the JSON representation of the object.
50
    /// </summary>
51
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
52
    /// <param name="value">The value.</param>
53
    /// <param name="serializer">The calling serializer.</param>
54
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
55
    {
56
      string text;
57

  
58
 44
      if (value is DateTime)
59
      {
60
 38
        DateTime dateTime = (DateTime)value;
61

  
62
 38
        if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
63
 38
          || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
64
 5
          dateTime = dateTime.ToUniversalTime();
65

  
66
 38
        text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
67
      }
68
#if !PocketPC && !NET20
69
 6
      else if (value is DateTimeOffset)
70
      {
71
 6
        DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
72
 6
        if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
73
 6
          || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
74
 5
          dateTimeOffset = dateTimeOffset.ToUniversalTime();
75

  
76
 6
        text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
77
      }
78
#endif
79
      else
80
      {
81
 0
        throw new Exception("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
82
      }
83

  
84
 44
      writer.WriteValue(text);
85
 44
    }
86

  
87
    /// <summary>
88
    /// Reads the JSON representation of the object.
89
    /// </summary>
90
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
91
    /// <param name="objectType">Type of the object.</param>
92
    /// <param name="existingValue">The existing value of object being read.</param>
93
    /// <param name="serializer">The calling serializer.</param>
94
    /// <returns>The object value.</returns>
95
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
96
    {
97
 39
      bool nullable = ReflectionUtils.IsNullableType(objectType);
98
 39
      Type t = (nullable)
99
 39
        ? Nullable.GetUnderlyingType(objectType)
100
 39
        : objectType;
101

  
102
 39
      if (reader.TokenType == JsonToken.Null)
103
      {
104
 6
        if (!ReflectionUtils.IsNullableType(objectType))
105
 4
          throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
106
 
107
 2
        return null;
108
      }
109

  
110
 33
      if (reader.TokenType != JsonToken.String)
111
 3
        throw new Exception("Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
112

  
113
 30
      string dateText = reader.Value.ToString();
114

  
115
 30
      if (string.IsNullOrEmpty(dateText) && nullable)
116
 1
        return null;
117

  
118
#if !PocketPC && !NET20
119
 29
      if (t == typeof(DateTimeOffset))
120
      {
121
 4
        if (!string.IsNullOrEmpty(_dateTimeFormat))
122
 0
          return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
123
        else
124
 4
          return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
125
      }
126
#endif
127

  
128
 25
      if (!string.IsNullOrEmpty(_dateTimeFormat))
129
 3
        return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
130
      else
131
 22
        return DateTime.Parse(dateText, Culture, _dateTimeStyles);
132
 29
    }
133
  }
134
}