Moment js time stamp

Viewed 152

I am using moment.js to parse my date time and I am getting totally confused.

If I do moment().toDate() I get:

Fri Aug 21 2020 21:52:48 GMT-0400 (Eastern Daylight Time)

which is exactly correct. I am showing this so that you know that moment is not pulling incorrect local time for me.

I have a time which looks like this that I pulling from a database:

2020-08-21T21:49:58.000Z

As you can see this is the same day as above but a slightly different time like 3 minutes ago.

If I do:

moment("2020-08-21T21:49:58.000Z").calendar()

it returns :

"Today at 5:49 PM"

which is incorrect.

However, if remove 0Z from the end of the time stamp and do this:

moment("2020-08-21T21:49:58.00").calendar()

I get

"Today at 9:49 PM"

which is correct.

I am guessing by looking at the format moment decides it is a UTC time and subtract 4 hours from it.

Therefore, I thought I would convert it back to utc() but when I do:

moment("2020-08-21T21:49:58.000Z").utc().calendar()

I get:

"Yesterday at 9:49 PM"

which decreases it by 24 hours and I am not sure why.

Is there a function that I can use to prevent it from assuming that the time is in UTC format?

Edit 1:

If I do moment().toDate() I get:

Sun Aug 23 2020 20:53:28 GMT-0400 (Eastern Daylight Time)

which is correct.

When I try to use the time stamp from today:

moment("2020-08-23T20:52:38.000Z").utc().calendar()

I am getting:

"Yesterday at 8:52 PM"

1 Answers

You could try to enable your moment object to local time mode:

moment("2020-08-21T21:49:58.000Z").local().calendar()
Related