我试图在模型上格式化日期类型属性,然后再显示它。这是我正在使用的代码:
// MODEL
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: String,
content: String,
author: { type: String, default: 'Vlad'},
postDate: { type: Date, default: Date.now }
});
ArticleSchema.methods.formatTitle = function() {
var link = this.title.replace(/\s/g, '-');
return '/article/' + link;
};
ArticleSchema.methods.snapshot = function() {
var snapshot = this.content.substring(0, 500);
return snapshot;
};
ArticleSchema.methods.dateString = function() {
var date = new Date(this.postDate);
return date.toDateString();
};
module.exports = mongoose.model('Article', ArticleSchema);
在客户端,我尝试使用以下方式显示格式化日期:
{{ article.dateString }}
但是,每当我加载包含此元素的视图时,我都会收到500错误:
Cannot call method 'toDateString' of undefined
EDIT1:我在我的视图中嵌入{{article.snapshot}}没有问题,但是当谈到Date对象时,我收到错误
EDIT2:使用console.log(article.dateString())记录dateString方法时,我得到以下内容:
Wed Sep 18 2013
EDIT3:这是我在使用dankohn提供的代码时得到的。它只是我,还是只是连续两次运行该方法?
this.postdate: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
parsed: 1379536022000
date: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
toString: Wed Sep 18 2013
Wed Sep 18 2013
this.postdate: undefined
parsed: NaN
date: Invalid Date
toString: Invalid Date
答案 0 :(得分:1)
我已经重写了这一点,以便清楚地说明日期内容失败的地方:
ArticleSchema.methods.dateString =
console.log('this.PostDate: ' + this.postDate)
var parsed = Date.parse(this.postDate)
console.log('parsed: ' + parsed)
var date = new Date(parsed);
console.log('date: ' + date)
var toString = date.toDateString();
comsole.log('toString: ' + toString)
return toString;
};
另外,如果这对您不起作用,我建议使用库moment,这比原生Javascript日期更容易使用。