Mykyta Halchenko
Mykyta Halchenko

Reputation: 798

MomentJS UTC date is not detected as utc inside momentjs

I have a date represented as a string:

const dateStr = "2022-09-29T00:00:00Z";

So this is UTC format with zero (equivalent to "2022-09-29T00:00:00+0000")

When I use momentJS it is converted to my local time(and this is fine), but my local time -3 hours, so by this example I have 22-09-28, this happens because momentJs doesn't recognize it as UTC, but it is UTC format - why? Please see the screenshot attached below, I mean _isUTC flag

enter image description here

Code I am testing below:

const dateStr = "2022-09-29T00:00:00Z";
const res = moment(dateStr)
const res1 = moment(dateStr).format('YYYY-MM-DD'); // will be 2022-09-28 because of -3 hours my timezone and it is not detected as UTC.
console.log(res);

P.S. I know that moment(dateStr).utc().format('YYYY-MM-DD') will work but can it be detected automatically?

Upvotes: 2

Views: 1697

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

While moment recognizes the input as a UTC date, it will still be converted to local time when using moment().

Moment's string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time.

I'd suggest using UTC mode, using the moment.utc() function, or using moment().utc().

While in UTC mode, all display methods will display in UTC time instead of local time.

This should give you the desired behavior:

const dateStr = "2022-09-29T00:00:00Z";
const dtUTC = moment.utc(dateStr);

console.log('UTC mode:');
console.log('dtUTC.format():', dtUTC.format());
console.log('_.isUTC:', dtUTC ._isUTC);
console.log('UTC offset:', dtUTC .format('Z'));

// Using the moment() constructor, the date will be recognized as UTC but converted to the local timezone:
console.log('\nLocal:');
const dtLocal = moment(dateStr );
console.log('dtLocal.format():', dtLocal.format());
console.log('_.isUTC:', dtLocal._isUTC);
console.log('UTC offset:', dtLocal.format('Z'));
.as-console-wrapper { max-height: 100% !important; }
   
<script src="https://momentjs.com/downloads/moment.js"></script>

Upvotes: 2

Related Questions