Statistics
| Branch: | Revision:

root / trunk / Pithos.Interfaces / PithosDateTimeConverter.cs @ 84b880b5

History | View | Annotate | Download (4.9 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PithosDateTimeConverter.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42
using System;
43
using System.Globalization;
44
using Newtonsoft.Json;
45
using Newtonsoft.Json.Converters;
46
using Newtonsoft.Json.Utilities;
47

    
48
namespace Pithos.Interfaces
49
{
50
    /// <summary>
51
    /// Converts a <see cref="DateTime"/> to and from a JavaScript date constructor (e.g. new Date(52231943)).
52
    /// </summary>
53
    public class PithosDateTimeConverter : DateTimeConverterBase
54
    {
55
        private DateTime _epoch = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc);
56

    
57
        /// <summary>
58
        /// Writes the JSON representation of the object.
59
        /// </summary>
60
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
61
        /// <param name="value">The value.</param>
62
        /// <param name="serializer">The calling serializer.</param>
63
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
64
        {
65
            double seconds;
66

    
67
            if (value is DateTime)
68
            {
69
                var dateTime = (DateTime)value;
70
                var utcDateTime = dateTime.ToUniversalTime();
71
                seconds = (utcDateTime - _epoch).TotalSeconds; ;
72
            }
73
            else if (value is DateTimeOffset)
74
            {
75
                var dateTimeOffset = (DateTimeOffset)value;
76
                var utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
77
                seconds= (utcDateTimeOffset.UtcDateTime - _epoch).TotalSeconds;
78
            }
79
            else
80
            {
81
                throw new Exception("Expected date object value.");
82
            }
83

    
84
            writer.WriteValue(seconds);
85
        }
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 property value of the JSON that is being converted.</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
            Type t = (IsNullableType(objectType))
98
                         ? Nullable.GetUnderlyingType(objectType)
99
                         : objectType;
100

    
101
            if (reader.TokenType == JsonToken.Null)
102
            {
103
                if (!IsNullableType(objectType))
104
                    throw new Exception(String.Format("Cannot convert null value to {0}.",objectType));
105

    
106
                return null;
107
            }
108

    
109
            var seconds = double.Parse(reader.Value.ToString()); //CultureInfo.InvariantCulture);
110

    
111
            DateTime d =  _epoch.AddSeconds(seconds);
112

    
113

    
114
            if (t == typeof(DateTimeOffset))
115
                return new DateTimeOffset(d);
116
            return d;
117
        }
118

    
119
        public static bool IsNullableType(Type t)
120
        {
121
            if (t== null)
122
                throw new ArgumentNullException("t");
123

    
124
            return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
125
        }
126
    }
127
}