Search code examples
mongodbmeteormomentjsmeteor-autoform

How to properly deal with GMT offsets / timezones in meteor with autoform and moment library


I'm running into issues working with dates/times with mongo and autoform.

I started with a migration from another DB system, where I had dates stored as strings.

the migration was in PHP and I used the following to convert to Mongo dates:

return new MongoDate(strtotime($date));

So, for example, I start with 7/30/1960 (july 30, 1960)

And In Mongodb, I see:

ISODate("1960-07-30T05:00:00.000+0000"),

And, when I view that in my table grid using a helper and the moment library:

Template.registerHelper("mdy", function (date) {
  if (date) {
    return moment(date).format('MM/DD/YYYY');
  }
});

I get: 07/30/1960

Then, I open that up in a form, using autoForm with a schema like this:

someDate: {
type: Date,
}

and still, I see 07/30/1960

but then I save that to the database, and look back in the database to see what is saved:

ISODate("1960-07-30T00:00:00.000+0000"),

(Note it has changed from T05 to T00)

and now when I display that in my table grid I see:

07/29/1960

But interestingly, if I open that record again in the autoform, it shows 07/30/1960

So there is obviously something going wrong with timezone, or GMT offset, or something like that

Anyone know what I'm missing?

EDIT: funny observation... I logged this question yesterday, Tuesday April 28, and today is Wednesday April 29, yet the question still says "asked today"

enter image description here

EDIT: adding mongodb tag ... you mongo guys can remove the tag if this is not a mongo issue!


Solution

  • The solution I found was to use moment.utc(date) for formatting the date instead of just moment(date).

    So, the helper would be:

    Template.registerHelper("mdy", function (date) {
      if (date) {
        return moment.utc(date).format('MM/DD/YYYY');
      }
    });
    

    Thanks to: http://blog.skylight.io/bringing-sanity-to-javascript-utc-dates-with-moment-js-and-ember-data/ for the push in the right direction!