16

Trying to understand the behaviour and difference between:

moment.utc(date) and moment(date).utc()

Using '2018-05-31' as a param:

moment.utc('2018-05-31').format() will give:

‌2018-05-31T00:00:00Z

while moment('2018-05-31').utc().format() will give:

2018-05-31T04:00:00Z

I am executing both in EST timezone.

inside
  • 3,047
  • 10
  • 49
  • 75
  • 4
    The former gives UTC midnight. The latter converts your local midnight into UTC. (I'm at GMT+2, the 2nd gives `2018-05-30T22:00:00Z`) –  May 30 '18 at 15:14

1 Answers1

23

The first moment.utc(String) parses your string as UTC, while the latter converts your moment instance to UTC mode.

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().

This brings us to an interesting feature of Moment.js. UTC mode.

See Local vs UTC vs Offset guide to learn more about UTC mode and local mode.

console.log( moment.utc('2018-05-31').format() );
console.log( moment('2018-05-31').utc().format() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112