I am using the following code to convert a server-side date-time to local time using Moment.js
moment(moment('Wed, 23 Apr 2014 09:54:51 +0000').format('lll')).fromNow()
But I am getting:
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
It seems i cannot get rid of it! How can I fix it?
If your date is passed to you from an API as
string
(like my issue), you can use a filter to convert the string to a date for moment. This will take care of the moment construction warning.Add it to the view:
The date construction in
moment
internally uses thenew Date()
in the javascript. Thenew Date()
construction recognizes the date string in either RFC2822 or ISO formats in all browsers. When constructing amoment
object with date not in these formats, the deprecation warning is thrown.Though the deprecation warnings are thrown, for some formats, the
moment
object will be successfully constructed in Chrome, but not in Firefox or Safari. Due to this, processing the date in Chrome may give results as expected(not all the time) and throwsInvalid Date
in others.Consider,
02.02.2018
,Chrome -
moment("02.02.2018")._d
->Fri Feb 02 2018 00:00:00 GMT+0530 (India Standard Time)
Firefox -
moment("02.02.2018")._d
->Invalid Date
Safari -
moment("02.02.2018")._d
->Invalid Date
So the
moment.js
is used at your own risk in case the recommended/standard formats are not used.To suppress the deprecation warnings,
moment
construction.Example :
moment("02.05.2018", "DD.MM.YYYY").format("DD MM YYYY");
Example :
moment("2018-02-01T18:30:00.000Z")
- ISO Formatmoment("Thu, 01 Feb 2018 18:30:00 GMT")
- RFC2822 Format - Format in Githubmoment.suppressDeprecationWarnings = true;
I suggest to overwrite the input fallback in moment.
As (3) will suppress all the warnings, (4) will suppress only the date construction fallback. Using (4), you will get
Invalid Date
as the internalnew Date()
is used and other deprecations can be seen in console, so moment can be upgraded or the deprecated methods can be replaced in the application.As an alternative, you can suppress showing the deprecation warning by setting
moment.suppressDeprecationWarnings = true;
To get rid of the warning, you need to either:
Pass in an ISO formatted version of your date string:
moment('2014-04-23T09:54:51');
Pass in the string you have now, but tell Moment what format the string is in:
moment('Wed, 23 Apr 2014 09:54:51 +0000', 'ffffd, DD MMM YYYY HH:mm:ss ZZ');
Convert your string to a JavaScript Date object and then pass that into Moment:
moment(new Date('Wed, 23 Apr 2014 09:54:51 +0000'));
The last option is a built-in fallback that Moment supports for now, with the deprecated console warning. They say they won't support this fallback in future releases. They explain that using
new Date('my date')
is too unpredictable.