Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Serializing/Deserializing dates to/from ISO 8601 format with Ember data

Ember Data is a persistence layer for Ember.Js. Without any configuration, Ember Data can load and save records and their relationships served via a RESTful JSON API, provided it follows certain conventions.

By default, Date in Ember Data is serialised to a UNIX timestamp. This is great for some backends, but it might be more suitable for some to deal with textual date formats like the ISO 8601. Fortunately, Ember Data makes it really easy to define custom transformers for serialising and deserializing stuff with REST requests.

To have an isodate transformer in Ember Data, all you need is the following:

App.IsodateTransform = DS.Transform.extend({  
  deserialize: function (serialized) {
    if (serialized) {
      return moment(serialized).toDate();
    }
    return serialized;
  },

  serialize: function (deserialized) {
    if (deserialized) {
      return moment(deserialized).format();
    }
    return deserialized;
  }
});

Now, you can define dates in your models with DS.attr('isodate'). Here I am using the wonderful Moment.js library for handling dates. You would, of course need to modify the definitions accordingly if you decide not to use it.