问题
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