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.
The moment(). utc() method is used to specify that the given Moment object's timezone would be displayed as UTC.
utc(); moment. utc can take params as number, string, moment, date etc. This method can be used when the date displayed has to be in UTC format.
getTime() returns the number of milliseconds since 1970-01-01. If you create a new Date using this number, ex: new Date(Date. getTime()); it will be UTC, however when you display it (ex: through the chrome dev tools console) it will appear to be your local timezone.
Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.
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 ofmoment()
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With