Javascript 如何在 Node.js 中格式化来自 Mongoose 的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7443142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:17:49  来源:igfitidea点击:

How do I format dates from Mongoose in Node.js?

javascriptdatemongodbnode.jsmongoose

提问by Ben Humphreys

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 Dateobjects or just raw strings.

我试过打电话.toString('yyyy-MM-dd')给他们,但没有任何改变。我不知道它们是Date对象还是只是原始字符串。

I've tried checking the Mongoose manual and googling a bunch, but not found anything yet.

我试过检查猫鼬手册并谷歌搜索一堆,但还没有找到任何东西。

Any ideas?

有任何想法吗?

回答by eloone

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,既可在节点中使用,也可在浏览器中使用,超级有用且易于使用。对于当前的问题,我在遵循所有文档要求后在节点中解决了这个问题:

var moment = require('moment');
var fomatted_date = moment(photo.date_published).format('YYYY-MM-DD');

with photo.date_publisheddirectly coming from mongoose.

photo.date_published从猫鼬直接来了。

回答by pkyeck

you have to create a Date object first:

你必须先创建一个 Date 对象:

var date = new Date(dateStr);  // dateStr you get from mongodb

var d = date.getDate();
var m = date.getMonth()+1;
// ...

回答by Juri

what about defining your schema like:

定义你的架构怎么样:

var someSchema = new Schema({
    title: String,
    created: Date
});

s.t. the date is stored as a Dateobject in your mongoDB. As a result, when you read it back you'll have a proper Dateobject on which you can work with the available methods.

st 日期作为Date对象存储在 mongoDB 中。因此,当您回读它时,您将拥有一个合适的Date对象,您可以在该对象上使用可用的方法。