简体   繁体   中英

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

在此处输入图像描述

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);

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM