I'm trying to change the format of the dates I'm getting from my Mongo database. Currently they look like this:
我想改变我从Mongo数据库得到的日期格式。目前它们看起来是这样的:
Fri Sep 16 2011 19:05:17 GMT+0900 (JST)
I've tried calling .toString('yyyy-MM-dd')
on them but nothing changes. I don't know if they're Date
objects or just raw strings.
我试过调用。tostring ('yyyy-MM-dd'),但是没有变化。我不知道它们是日期对象还是原始字符串。
I've tried checking the Mongoose manual and googling a bunch, but not found anything yet.
我试过查看Mongoose手册,在谷歌上搜了一大堆,但还是一无所获。
Any ideas?
什么好主意吗?
3 个解决方案
#1
16
you have to create a Date object first:
您必须首先创建一个日期对象:
var date = new Date(dateStr); // dateStr you get from mongodb
var d = date.getDate();
var m = date.getMonth()+1;
// ...
#2
15
A modern way to do this is to use momentjs, both usable in node and in the browser, super useful and simple to use. For the current problem I solved it like this in node after following all the docs requirements :
一种现代的方法是使用momentjs,在node和浏览器中都可以使用,非常有用且使用简单。对于目前的问题,我按照文档的要求在node这样解决:
var moment = require('moment');
var fomatted_date = moment(photo.date_published).format('YYYY-DD-MM');
with photo.date_published
directly coming from mongoose.
与照片。date_published直接来自mongoose。
#3
8
what about defining your schema like:
如何定义您的模式,比如:
var someSchema = new Schema({
title: String,
created: Date
});
s.t. the date is stored as a Date
object in your mongoDB. As a result, when you read it back you'll have a proper Date
object on which you can work with the available methods.
日期被存储为mongoDB中的一个日期对象。因此,当您将它读回来时,您将拥有一个合适的Date对象,您可以在该对象上使用可用的方法。
#1
16
you have to create a Date object first:
您必须首先创建一个日期对象:
var date = new Date(dateStr); // dateStr you get from mongodb
var d = date.getDate();
var m = date.getMonth()+1;
// ...
#2
15
A modern way to do this is to use momentjs, both usable in node and in the browser, super useful and simple to use. For the current problem I solved it like this in node after following all the docs requirements :
一种现代的方法是使用momentjs,在node和浏览器中都可以使用,非常有用且使用简单。对于目前的问题,我按照文档的要求在node这样解决:
var moment = require('moment');
var fomatted_date = moment(photo.date_published).format('YYYY-DD-MM');
with photo.date_published
directly coming from mongoose.
与照片。date_published直接来自mongoose。
#3
8
what about defining your schema like:
如何定义您的模式,比如:
var someSchema = new Schema({
title: String,
created: Date
});
s.t. the date is stored as a Date
object in your mongoDB. As a result, when you read it back you'll have a proper Date
object on which you can work with the available methods.
日期被存储为mongoDB中的一个日期对象。因此,当您将它读回来时,您将拥有一个合适的Date对象,您可以在该对象上使用可用的方法。