Deprecation warning: moment construction falls bac

2019-05-12 05:28发布

问题:

I am attempting to convert this datetime

150423160509 //this is utc datetime

To the following format:

2015-04-24 00:05:09 //local timezone

by using the moment.js

var moment = require('moment-timezone');


var a = moment.tz('150423160509', "Asia/Taipei");
console.log( a.format("YYYY-MM-DD H:m:s") );

but it gives me this error

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release

回答1:

You need to tell moment how to parse your date format, like this:

var parsedDate = moment.utc("150423160509", "YYMMDDHHmmss");
var a = parsedDate.tz("Asia/Taipei");

// I'm assuming you meant HH:mm:ss here
console.log( a.format("YYYY-MM-DD HH:mm:ss") );


回答2:

This is what i found when I typed "moment construction falls back to js Date" in Google. (From a post of Joe Wilson)

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.

Hope that helped ;)