moment.js deprecation warning on ISO string?

2019-08-12 01:26发布

I've got the following javascript code utilizing the moment.js library. We've been having issues with conversions to/from utc. The code below returns this result:

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.
1: 2014-11-17T19:16:00+00:00
2: 2014-11-17T19:16:00+00:00
3: 2014-11-17T13:16:00-06:00

Why would the first one return the same but give the deprecated warning? I'm using an ISO string.

Code:

var r = {Start:'2014-11-17T20:47:00Z', End:'2014-11-17T19:16:00Z'};

console.log(moment(r.Start).local()); 

            var e = moment(r.Start);
            var f = moment(r.End);

 var res = {exDate:      moment(e).format("MM/DD/YYYY"),
            exStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
            exEndTime:   moment(f).format("MM/DD/YYYY hh:mm A")}

console.log(res );                   
console.log("1: " + moment(res.exEndTime).utc().format());
console.log("2: " + moment.utc(res.exEndTime).format());
console.log("3: " + moment(res.exEndTime).format()); // testing default local format.

标签: momentjs
2条回答
看我几分像从前
2楼-- · 2019-08-12 01:39

Errors are because of wrapping date already wrapped with moment. You should use moment like this:

var r = {Start:'2014-11-17T20:47:00Z', End:'2014-11-17T19:16:00Z'};
console.log(moment(r.Start).local()); 

var e = moment(r.Start);
var f = moment(r.End);

var res = {
    exDate: e.format("MM/DD/YYYY"),
    exStartTime: e.format("MM/DD/YYYY hh:mm A"),
    exEndTime: f.format("MM/DD/YYYY hh:mm A")
}

console.log(res );                   
console.log("1: " + f.utc().format());
console.log("2: " + f.format());
console.log("3: " + f.format()); // testing default local format.
查看更多
闹够了就滚
3楼-- · 2019-08-12 01:44

The errors are produced by the last three lines. For example, when you call moment(res.exEndTime) is already a string formatted as MM/DD/YYYY hh:mm A. You are also calling moment redundantly. Essentially, you have:

moment(moment(moment('2014-11-17T19:16:00Z')).format("MM/DD/YYYY hh:mm A")).format()

That's too many moments!

查看更多
登录 后发表回答