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
1.5k views
in Technique[技术] by (71.8m points)

javascript - Sort with moment.js: Deprecation warning: value provided is not in a recognized RFC2822 or ISO format

I parse dates I get from an API with Moment, and I need to sort the array when I'm done collecting the data. I currently have this:

myobject.name = name;
myobject.time = Moment(ajaxinfo.startdate).format('DD/MM/YYYY');
array.push(myobject);
// ... more data is added ...
array.sort((left, right) => {
    return Moment.utc(left.time).diff(Moment.utc(right.time));
});

ajaxinfo.startdate is a string that I get from an API, and it looks like "2018-01-28T13:00:00+00:00"

But the above code doesn't work. It gives me a warning:

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. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

How can I make it work?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As stated by others the format "DD/MM/YYYY" is not an ISO 8601 format and the resulting strings can be ambiguous.

You should really work with Date or moment objects, not strings.

So don't call format when you store the dates in your array objects. If ever you need to render the date, call format at that very time.

const Moment = moment;

// Sample strings
var ajaxinfos = [
    { name: "x", startdate: "2018-01-28T13:00:00+00:00" },
    { name: "y", startdate: "2018-01-26T18:00:00+00:00" }
];

const array = [];
for (const ajaxinfo of ajaxinfos) {
    const myobject = {};
    myobject.name = ajaxinfo.name;
    myobject.time = Moment(ajaxinfo.startdate);  // don't call format
    array.push(myobject);
}

// No more need to convert strings to dates while sorting:
array.sort((left, right) => left.time.diff(right.time));
console.log(array);

// Whenever you need to format:
const formatted = array.map(info => info.time.format("MM/DD/YYYY"));
console.log(formatted);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>

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

...