forked from JSONAPIdotNET/JSONAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateTimeAttributeValueConverter.cs
More file actions
48 lines (44 loc) · 1.51 KB
/
Copy pathDateTimeAttributeValueConverter.cs
File metadata and controls
48 lines (44 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace JSONAPI.Core
{
/// <summary>
/// Implementation of <see cref="IAttributeValueConverter" /> suitable for
/// use converting between DateTime CLR properties and ISO8601 string values.
/// </summary>
public class DateTimeAttributeValueConverter : IAttributeValueConverter
{
private readonly PropertyInfo _property;
private readonly bool _isNullable;
/// <summary>
/// Creates a new DateTimeAttributeValueConverter
/// </summary>
/// <param name="property"></param>
/// <param name="isNullable"></param>
public DateTimeAttributeValueConverter(PropertyInfo property, bool isNullable)
{
_property = property;
_isNullable = isNullable;
}
public JToken GetValue(object resource)
{
var value = _property.GetValue(resource);
if (value != null) return ((DateTime) value).ToString("s");
if (_isNullable) return null;
return "0001-01-01";
}
public void SetValue(object resource, JToken value)
{
if (value == null || value.Type == JTokenType.Null)
{
_property.SetValue(resource, _isNullable ? (DateTime?)null : new DateTime());
}
else
{
var dateTimeValue = value.Value<DateTime>();
_property.SetValue(resource, dateTimeValue);
}
}
}
}