javascript - 用 moment.js : Deprecation warning: value provided is not in a recognized RFC2822 or ISO format 排序

标签 javascript sorting date momentjs

我使用 Moment 解析从 API 获得的日期,我需要在完成数据收集后对数组进行排序。我目前有这个:

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 是我从 API 获取的字符串,它看起来像 "2018-01-28T13:00:00+00:00"

但是上面的代码不起作用。它给了我一个警告:

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.

我怎样才能让它发挥作用?

最佳答案

正如其他人所述,格式“DD/MM/YYYY”不是 ISO 8601 格式,生成的字符串可能不明确。

你真的应该使用 Date 或 moment 对象,而不是字符串。

因此,当您将日期存储在数组对象中时,不要调用 format。如果您需要呈现日期,请在那个时候调用 format

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>

关于javascript - 用 moment.js : Deprecation warning: value provided is not in a recognized RFC2822 or ISO format 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48692757/

相关文章:

java - 如何对链表节点数组进行从高到低排序(基于float值)

JQuery tablesorter 插件 - 修改行后更新排序

python - 如何从 Dataframe 对象字段中提取日期值

javascript - 在 forEach 循环中创建一个对象并将其推送到数组中

mysql - 如何排序由状态字段链接在一起的记录

用于匹配整个单词的 Javascript 正则表达式

php - 使用 php 将时间转换为不同的时区

ios - 来自 "24:00"字符串的 DateFormatter 返回 Nil

javascript - 在 Angular js 中嵌入来自 json 响应的 Youtube 视频 url 和 Vimeo 视频 url 时的问题

javascript - 单击按钮时内容过滤器跳转