Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - “Deprecation warning: moment construction falls back to js Date” when trying to convert RFC2822 date in moment.js

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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', 'ddd, 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...