Syncfusion grid datetime format fixed

We use the data grid from Syncfusion and it is awesome! It serialises the data on the server and puts it in the page as json. Now more postbacks to get extra data or for sorting / filtering / other expected user feature.

Unfortunately the formatting of datetime field was broken in the version we are using. After some digging we found that altering the json serialisation would fix the issue. See code below

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Syncfusion.JavaScript.Shared.Serializer;
using System;

namespace Utils {
    /// <summary>
    /// big data serializer, uses Newtonsoft.Json to get over 4Mb limit
    /// and serializes datatime fields for easy formatting
    /// </summary>
    public class BigDataSerializer : IDataSourceSerializer {
        // format DateTime as milliseconds from 1-1-1970 (java thing)
        public class MyDateTimeFormat : DateTimeConverterBase {
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
                var milliseconds = ((DateTime)value).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
                writer.WriteRawValue(string.Format("new Date({0})", milliseconds));
            }

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
                throw new NotImplementedException();
            }
        }

        // uses the MyDateTimeFormat class
        public string Serialize(object obj) {
            var result = JsonConvert.SerializeObject(obj,
                                Formatting.None,
                                new MyDateTimeFormat());
            return result;
        }
    }
}

In the Razor file that uses the data grid we put the following code at the start. This makes sure the BigDataSerializer is used and DataTime is formatted correct.

@{
    Syncfusion.JavaScript.Shared.Serializer.DataManagerConverter.Serializer = new Utils.BigDataSerializer();
}

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.