moment.js: Deprecation warning: value provided is not in a recognized RFC2822 or ISO format [duplicate]

浪尽此生 提交于 2021-02-11 12:16:55

问题


I am getting date as input from an external source and it is a string,

const a = '08-01-2019';

And required format for me is 'MM-DD-YYYY',

const outputDateFormat = 'MM-DD-YYYY';

And I am using moment.js and doing below manipulations on that date like adding a year and decreasing a day,

//adding a year 

const a = moment(a).add(1, 'years').add(-1, 'days').format(outputDateFormat);

for the above line, I am getting ,

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format.
moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.

I mean, Converting to my output required format using moment is giving the deprecated warning.

const finalDate = moment(a).format(outputDateFormat); - Resulting depricated warning

So, I have tried using new Date() as below to avoid warnings.

//adding a year - approach #1

    const a = moment(new Date(a)).add(1, 'years').add(-1, 'days').format(outputDateFormat);

This is not returning any error but I am not considering this approach of new Date() as my code should work across timezones and locales. And if we use new Date() code might not work properly across timezones and locales? can anyone suggest?

And so, I have followed this approach # 2,

//adding a year - approach #2

    const a = moment('2019-01-08').add(1, 'years').add(-1, 'days').format(outputDateFormat);

Where I am giving date format in the form 'YYYY-MM-DD' instead of my input date format 'MM-DD-YYYY'.

This is also, not returning any warning and code is working fine. Will this work across timezones and locales?

Can anyone suggest me to use approach #1 or #2 to make my code work across timezones/locales without any errors/momentjs warnings?

Do I need to use moment.utc here to make code work across timezones? I think UTC is not required, As I am not having any time-related validations.

I mean moment.utc() is not required I guess as there is no time component for me, please suggest.

moment.utc('2019-01-08').add(1, 'years').add(-1, 'days').format(outputDateFormat)

Or else can anyone suggest a better approach than this to make code work across timezones and locales without any issues?


回答1:


You need to specify the format of the input when construct new moment object

const moment = require('moment')

const a = '08-01-2019';
const outputDateFormat = 'MM-DD-YYYY';

const b = moment(a, 'MM-DD-YYYY').add(1, 'years').add(-1, 'days').format(outputDateFormat);
console.log(b);


来源:https://stackoverflow.com/questions/58759601/moment-js-deprecation-warning-value-provided-is-not-in-a-recognized-rfc2822-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!