[英]Cannot overwrite date with moment.js
I have a collection of activities and MongoDB.我有一系列活动和 MongoDB。 Activities also have a date.活动也有日期。 I'm trying to dynamically build a table with all activities saved in my collection.我正在尝试动态构建一个表,其中包含保存在我的集合中的所有活动。 Therefor I want to change the format of the date with moment.js right before I send the array of JSON objects to my jade file.因此,我想在将 JSON 对象数组发送到我的 jade 文件之前使用 moment.js 更改日期格式。
I tried to make a new results array and send this one over to my jade file.我尝试创建一个新的结果数组并将其发送到我的玉文件中。
router.get('/', function(req, res, next) {
activitiesController.getActivities(function(results) {
if(!results) {
results = [];
}
for(var key in results) {
results[key].date = moment(results[key].date).format('ddd, hA');
}
res.render('index', {
activities: results
})
});
});
This is how the results array looks:这是结果数组的外观:
[{
"_id" : ObjectId("56fe2c0d7afcafa412ae19c2"),
"title" : "Fitnessstudios",
"category" : "Sport",
"time" : 2,
"date" : ISODate("2016-03-30T00:00:00.000Z"),
"__v" : 0
}]
Your problem is that the value you are passing to moment.js is:您的问题是您传递给 moment.js 的值是:
ISODate("2016-03-30T00:00:00.000Z")
when it wants just the date string part:当它只需要日期字符串部分时:
"2016-03-30T00:00:00.000Z"
So get just the date string and pass that, the snippet below shows how to do that.所以只获取日期字符串并传递它,下面的代码片段展示了如何做到这一点。
var dateString = 'ISODate("2016-03-30T00:00:00.000Z")'.replace(/^[^\\"]+\\"([^\\"]+)\\".*$/,'$1'); document.write(dateString);
moment.js will likely parse an ISO string just fine without further help, however I think it's much better to tell it the format, so you should use something like: moment.js 可能会在没有进一步帮助的情况下很好地解析 ISO 字符串,但是我认为告诉它格式会更好,因此您应该使用以下内容:
var dateString = results[key].date.replace(/^[^\"]+\"([^\"]+)\".*$/,'$1');
results[key].date = moment(dateString,'YYYY-MM-DDThh:mm:ss.sssZ').format('ddd, hA');
// Wed, 10AM
And you should not use for..in over an array, you may find properties other than those you expect and in a different order.并且您不应该在数组上使用for..in ,您可能会以不同的顺序找到您期望的属性以外的属性。 Use a plain for , while or do loop or one of the looping methods like forEach , map , etc. as appropriate.根据需要使用普通的for 、 while或do循环或循环方法之一,如forEach 、 map等。
Change this:改变这个:
moment(results[key].date).format('ddd, hA');
to到
moment(new Date(results[key].date.toString()),moment.ISO_8601).format('ddd, hA');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.