You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

194 lines
7.4 KiB

  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.Globalization;
  27. using Newtonsoft.Json.Utilities;
  28. namespace Newtonsoft.Json.Converters
  29. {
  30. /// <summary>
  31. /// Converts a <see cref="DateTime"/> to and from the ISO 8601 date format (e.g. <c>"2008-04-12T12:53Z"</c>).
  32. /// </summary>
  33. internal class IsoDateTimeConverter : DateTimeConverterBase
  34. {
  35. private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
  36. private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
  37. private string _dateTimeFormat;
  38. private CultureInfo _culture;
  39. /// <summary>
  40. /// Gets or sets the date time styles used when converting a date to and from JSON.
  41. /// </summary>
  42. /// <value>The date time styles used when converting a date to and from JSON.</value>
  43. public DateTimeStyles DateTimeStyles
  44. {
  45. get => _dateTimeStyles;
  46. set => _dateTimeStyles = value;
  47. }
  48. /// <summary>
  49. /// Gets or sets the date time format used when converting a date to and from JSON.
  50. /// </summary>
  51. /// <value>The date time format used when converting a date to and from JSON.</value>
  52. public string DateTimeFormat
  53. {
  54. get => _dateTimeFormat ?? string.Empty;
  55. set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
  56. }
  57. /// <summary>
  58. /// Gets or sets the culture used when converting a date to and from JSON.
  59. /// </summary>
  60. /// <value>The culture used when converting a date to and from JSON.</value>
  61. public CultureInfo Culture
  62. {
  63. get => _culture ?? CultureInfo.CurrentCulture;
  64. set => _culture = value;
  65. }
  66. /// <summary>
  67. /// Writes the JSON representation of the object.
  68. /// </summary>
  69. /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
  70. /// <param name="value">The value.</param>
  71. /// <param name="serializer">The calling serializer.</param>
  72. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  73. {
  74. string text;
  75. if (value is DateTime dateTime)
  76. {
  77. if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
  78. || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
  79. {
  80. dateTime = dateTime.ToUniversalTime();
  81. }
  82. text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
  83. }
  84. #if !NET20
  85. else if (value is DateTimeOffset dateTimeOffset)
  86. {
  87. if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
  88. || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
  89. {
  90. dateTimeOffset = dateTimeOffset.ToUniversalTime();
  91. }
  92. text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
  93. }
  94. #endif
  95. else
  96. {
  97. throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
  98. }
  99. writer.WriteValue(text);
  100. }
  101. /// <summary>
  102. /// Reads the JSON representation of the object.
  103. /// </summary>
  104. /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
  105. /// <param name="objectType">Type of the object.</param>
  106. /// <param name="existingValue">The existing value of object being read.</param>
  107. /// <param name="serializer">The calling serializer.</param>
  108. /// <returns>The object value.</returns>
  109. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  110. {
  111. bool nullable = ReflectionUtils.IsNullableType(objectType);
  112. if (reader.TokenType == JsonToken.Null)
  113. {
  114. if (!nullable)
  115. {
  116. throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
  117. }
  118. return null;
  119. }
  120. #if !NET20
  121. Type t = (nullable)
  122. ? Nullable.GetUnderlyingType(objectType)
  123. : objectType;
  124. #endif
  125. if (reader.TokenType == JsonToken.Date)
  126. {
  127. #if !NET20
  128. if (t == typeof(DateTimeOffset))
  129. {
  130. return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value);
  131. }
  132. // converter is expected to return a DateTime
  133. if (reader.Value is DateTimeOffset offset)
  134. {
  135. return offset.DateTime;
  136. }
  137. #endif
  138. return reader.Value;
  139. }
  140. if (reader.TokenType != JsonToken.String)
  141. {
  142. throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
  143. }
  144. string dateText = reader.Value.ToString();
  145. if (string.IsNullOrEmpty(dateText) && nullable)
  146. {
  147. return null;
  148. }
  149. #if !NET20
  150. if (t == typeof(DateTimeOffset))
  151. {
  152. if (!string.IsNullOrEmpty(_dateTimeFormat))
  153. {
  154. return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
  155. }
  156. else
  157. {
  158. return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
  159. }
  160. }
  161. #endif
  162. if (!string.IsNullOrEmpty(_dateTimeFormat))
  163. {
  164. return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
  165. }
  166. else
  167. {
  168. return DateTime.Parse(dateText, Culture, _dateTimeStyles);
  169. }
  170. }
  171. }
  172. }