MongoDB, new Date(), and showing time with moment.js?

I’m getting some odd times when I run my date through moment.js

The times are 3 hours ahead of my local time. Should I be passing an option to moment.js? Or should I be passing an option when I’m creating the date and inserting into mongodb?

on insertion:

  createdAt: {
    type: Date,
    autoValue: function() {
      // returns a date only initial insert, ie the date it was created at
        if (this.isInsert && (!this.isSet || this.value.length === 0)) {
            return new Date()

my moment.js function:

export const formatTime = (createdAt) => {
  	const thisMoment = moment.utc(createdAt).format("h:mm");
    return thisMoment;

the format is correct but the timezone (I guess?) is 3 hours ahead.

Do I really need an additional package to get the correct time?

and is there a good pattern for passing in the current user’s timezone dynamically?

Try this?

const thisMoment = moment(createdAt).format("h:mm");

From the moment docs:

By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().

1 Like