简体   繁体   中英

Cannot overwrite date with moment.js

I have a collection of activities and 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.

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:

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:

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. Use a plain for , while or do loop or one of the looping methods like forEach , map , etc. as appropriate.

Change this:

moment(results[key].date).format('ddd, hA');

to

moment(new Date(results[key].date.toString()),moment.ISO_8601).format('ddd, hA');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM