Click here to Skip to main content
15,886,049 members
Articles / Programming Languages / Javascript
Article

Custom Dates JavaScript Serializer

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
20 Jun 2013CPOL1 min read 25K   10   1
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:

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionIDictionary<string>? Pin
Ken Granderson12-Aug-13 5:36
Ken Granderson12-Aug-13 5:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.