简体   繁体   中英

Cannot read property 'getDate'

I'm using keystone for my project. In 'Post' database there is publishedDate and I want to format it with code under.

function formatDate(date) {
    var monthNames = [
        "Ocak", "Şubat", "Mart",
        "Nisan", "Mayıs", "Haziran", "Temmuz",
        "Ağustos", "Eylül", "Ekim",
        "Kasım", "Aralık"
    ];

    var day = date.getDate();
    var monthIndex = date.getMonth();
    var year = date.getFullYear();

    return day + ' ' + monthNames[monthIndex] + ' ' + year;
}


var q = keystone.list('Post').model.findOne({
        state: 'published',
        slug: locals.filters.post,
    }).populate('author categories');

    q.exec(function (err, result) {
        Object.keys(result).forEach(function (key) {
            var element = result[key];              
            element.newDate = formatDate(element.publishedDate);
        });

        locals.data.post = result;
        next(err);
    });

});

When I run project an error occurs. But I know 'publishedDate' is a Date value.

 Mongoose model 'error' event fired on 'Post' with error:
 Cannot read property 'getDate' of undefined TypeError: Cannot read property 'getDate' of undefined

From you code:

var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();

are you sure in the date object you really have a getDate() , date.getMonth() , getFullYear() because I haven't seen where you instantiated your date new Date() .

Maybe you might want to go through this, it might help.

  var today = new Date(); var day = today.getDate(); var month = today.getMonth()+1; //January is 0! var year = today.getFullYear(); if(day<10) { day = `0${day}` } if(month<10) { month = `0${month}` } today = `${month} / ${day} / ${year}`; alert(`Today's date is "${today}"`); 

Replace

var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();

Into

var day = new Date(date).getDate();
var monthIndex = new Date(date).getMonth();
var year = new Date(date).getFullYear();

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