This repository has been archived by the owner on May 25, 2021. It is now read-only.
/
DateTypeConverter.cs
105 lines (81 loc) · 2.45 KB
/
DateTypeConverter.cs
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
namespace FluentCassandra.Types
{
internal class DateTypeConverter : CassandraObjectConverter<DateTimeOffset>
{
private static readonly DateTimeOffset UnixStart = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
public static long ToUnixTime(DateTimeOffset dt)
{
// this was changed from .NET Ticks to the Unix Epoch to be compatible with other cassandra libraries
return Convert.ToInt64(Math.Floor((dt - UnixStart).TotalMilliseconds));
}
public static DateTimeOffset FromUnixTime(long ms)
{
// this was changed from .NET Ticks to the Unix Epoch to be compatible with other cassandra libraries
return UnixStart.AddMilliseconds(ms);
}
public override bool CanConvertFrom(Type sourceType)
{
if (sourceType == typeof(DateTimeOffset))
return true;
if (sourceType == typeof(byte[]))
return true;
switch (Type.GetTypeCode(sourceType))
{
case TypeCode.DateTime:
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
public override bool CanConvertTo(Type destinationType)
{
if (destinationType == typeof(DateTimeOffset))
return true;
if (destinationType == typeof(byte[]))
return true;
switch (Type.GetTypeCode(destinationType))
{
case TypeCode.DateTime:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.String:
return true;
default:
return false;
}
}
public override DateTimeOffset ConvertFromInternal(object value)
{
if (value is DateTimeOffset)
return (DateTimeOffset)value;
if (value is byte[])
return FromUnixTime(((byte[])value).FromBytes<long>());
if (value is long)
return FromUnixTime((long)value);
if (value is ulong)
return FromUnixTime(Convert.ToInt64((ulong)value));
if (value is DateTime)
return new DateTimeOffset((DateTime)value);
return default(DateTimeOffset);
}
public override object ConvertToInternal(DateTimeOffset value, Type destinationType)
{
if (destinationType == typeof(DateTimeOffset))
return value;
if (destinationType == typeof(byte[]))
return ToUnixTime(value).ToBytes();
if (destinationType == typeof(long))
return ToUnixTime(value);
if (destinationType == typeof(ulong))
return (ulong)ToUnixTime(value);
if (destinationType == typeof(DateTime))
return value.LocalDateTime;
if (destinationType == typeof(string))
return value.ToString("u");
return null;
}
}
}