Last active
February 19, 2018 11:46
-
-
Save igorkulman/31c91704fa93870de4ee to your computer and use it in GitHub Desktop.
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
/// <summary> | |
/// Custom DateTime JSON serializer/deserializer | |
/// </summary> | |
public class CustomDateTimeConverter : DateTimeConverterBase | |
{ | |
/// <summary> | |
/// DateTime format | |
/// </summary> | |
private const string Format = "dd. MM. yyyy HH:mm"; | |
/// <summary> | |
/// Writes value to JSON | |
/// </summary> | |
/// <param name="writer">JSON writer</param> | |
/// <param name="value">Value to be written</param> | |
/// <param name="serializer">JSON serializer</param> | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
writer.WriteValue(((DateTime)value).ToString(Format)); | |
} | |
/// <summary> | |
/// Reads value from JSON | |
/// </summary> | |
/// <param name="reader">JSON reader</param> | |
/// <param name="objectType">Target type</param> | |
/// <param name="existingValue">Existing value</param> | |
/// <param name="serializer">JSON serialized</param> | |
/// <returns>Deserialized DateTime</returns> | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
if (reader.Value == null) | |
{ | |
return null; | |
} | |
var s = reader.Value.ToString(); | |
DateTime result; | |
if (DateTime.TryParseExact(s, Format, CultureInfo.InvariantCulture,DateTimeStyles.None, out result)) | |
{ | |
return result; | |
} | |
return DateTime.Now; | |
} | |
} |
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
[JsonConverter(typeof(CustomDateTimeConverter))] | |
public DateTime? PurchaseDate { get; set; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment