Data: When saving to server, Date attribute loses time zone information

Created on 12 Sep 2012  路  9Comments  路  Source: emberjs/data

A Date object is always sent as a GMT string, which loses the Date's time zone information

Bug Needs Bug Verification

All 9 comments

Here's an attempt to do an ISO 8601 with Timezone

var toTransform = function(d) {
  if(d instanceof Date) {
    var utc = new Date(d - d.getTimezoneOffset() * 60000);
    var zone = d.toTimeString().match(/GMT([0-9:\-\+]+)/)[1];
    return utc.toISOString().replace(/Z$/, zone);
  } else {
    return null;
  }
};

Is it related to #386 #387 ?

@sly7-7 @rykov i believe the PR i put in will fix this w/ the default transforms

Can you point me to the code to which you're referring? I'm having trouble finding changes to the existing algorithm that converts to RFC 3339 format of UTC time.

I can confirm this, if it's not a bug it's at least unexpected behavior:

test('Date attributes serializes as Date toString()', function() {

    App.Foo = DS.Model.extend({
        foo: DS.attr('date')
    });

    var date = new Date();
    var record = App.Foo.createRecord({foo:date});
    var serialized = record.serialize();

    equal(serialized.foo, date.toString());
});
Expected:       "Fri Feb 08 2013 13:28:58 GMT+0100 (CET)"
Result:         "Fri, 08 Feb 2013 12:28:58 GMT"

I'm already using the momentjs library so I created a new transform using that:

DS.JSONTransforms.moment = {
    deserialize:function (serialized) {
        if (serialized) {
            return moment(serialized).toDate();
        }

        return null;
    },

    serialize:function (date) {
        if (date) {
            var m = moment(date);

            if (m && m.isValid()) {
                return m.format(App.API_DATETIME_FORMAT);
            }
        }

        return null;
    }
};

I'm not sure this approach is fool proof but it seems to solve my immediate problem at least.

Edit: Updated with slightly safer version

Just observed this issue. Why not just use the epoch timestamp with Date.getTime() and new Date(timestamp) as serialization and deserialization? This is much easier than messing around with Strings.

Epoch timestamp loses time-zone information, which I need in my case.

If someone wants to submit a PR for this, we can definitely consider it. For now, you can just overwrite the default date transform to handle your specific case.

Was this page helpful?
0 / 5 - 0 ratings