65.9K
CodeProject is changing. Read more.
Home

Custom Dates JavaScript Serializer

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (3 votes)

Jun 20, 2013

CPOL

1 min read

viewsIcon

25487

Custom dates JavaScript serializer

Introduction

I've been developing software for 20 years now, and I've come across several instances where client side generated dates would get me in trouble.

A client of my company was a year younger on the west coast, because his DOB was coded XX/XX/XXXX 12:00:00

The browser in an user located in San Francisco would translate that date as a year younger than the one in New York.

Also, working with Knockout.js, I've found that serialization of Dates can be a problem.

You can implement custom bindings to solve it with Knockout, but I felt a server side solution was preferable.

The good news is that .NET provides a very elegant and easy way to implement the desired behavior.

Create a class deriving from  System.Web.Script.Serialization namespace.JavaScriptSerializer.

Override the key methods of that class and plugin your own implementation for any Date format you feel comfortable working with.

You can control the format of the date in the DateStringJSONConverter class, both on the Serialize and Deserialize method. Look at the code given below:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

    // Your Organization serializer. Override the key methods for the desired date format.
    // This example formats the date as MM/dd/yyyy
    public class YourOrg_JavaScriptSerializer : JavaScriptSerializer
    {
        public YourOrg_JavaScriptSerializer()
            : base()
        {
            this.RegisterConverters(new JavaScriptConverter[] { new DateStringJSONConverter() });
        }
    }

    public class DateStringJSONConverter : JavaScriptConverter
    {
        private List<type> supportedTypes;

        public DateStringJSONConverter()
        {
            supportedTypes = new List<type>(1);
            supportedTypes.Add(typeof(DateTime));
        }

        public override object Deserialize(IDictionary<string> 
        dictionary, Type type, JavaScriptSerializer serializer)
        {
            DateTime dt = DateTime.ParseExact(dictionary
            ["DateString"].ToString(), "MM/dd/yyyy", null);

            return dt;
        }

        public override IDictionary<string> Serialize(object obj, JavaScriptSerializer serializer)
        {
            DateTime dt = Convert.ToDateTime(obj);

            Dictionary<string> dicDateTime = new Dictionary<string>(1);
            dicDateTime.Add("DateString", dt.ToString("MM/dd/yyyy"));

            return dicDateTime;
        }

        public override IEnumerable<type> SupportedTypes
        {
            get { return this.supportedTypes; }
        }
    }

// In your xhr layer, replace the standard Javascript serializer with your own.
// var javaScriptSerializer = new JavaScriptSerializer(); Don't use the standard serializer use below

//var javaScriptSerializer = new YourOrg_JavaScriptSerializer();
// Serialize your model data: javaScriptSerializer.Serialize(model.Data);

Now every consumer of your app around the globe will deal with the same standard time taken from your servers.

Any comments/enhancements are more than welcome.

Hope this helps someone.

Credits

  • Greg Conway