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

发布于 2024-12-04 22:23:28 字数 246 浏览 1 评论 0原文

我正在尝试更改从 Mongo 数据库获取的日期的格式。目前它们看起来像这样:

Fri Sep 16 2011 19:05:17 GMT+0900 (JST)

我尝试对它们调用 .toString('yyyy-MM-dd') 但没有任何变化。我不知道它们是 Date 对象还是原始字符串。

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

有什么想法吗?

I'm trying to change the format of the dates I'm getting from my Mongo database. Currently they look like this:

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.

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

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

给我一枪 2024-12-11 22:23:28

一种现代的方法是使用 momentjs,既可以在节点中使用,也可以在浏览器中使用,超级有用且简单使用。对于当前的问题,我在遵循所有文档要求后在节点中解决了这个问题:

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

直接来自猫鼬的 photo.date_published

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 :

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

with photo.date_published directly coming from mongoose.

み青杉依旧 2024-12-11 22:23:28

您必须首先创建一个 Date 对象:

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

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

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;
// ...
尝蛊 2024-12-11 22:23:28

定义你的架构怎么样:

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

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

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.

梦在深巷 2024-12-11 22:23:28

只需添加

date: { type: String, default: Date }

输出将为: { "date": "Sat Nov 28 2020 22:57:38 GMT+0530 (India Standard Time)" }

Just Simply Add

date: { type: String, default: Date }

Output will be: { "date": "Sat Nov 28 2020 22:57:38 GMT+0530 (India Standard Time)" }

晨曦慕雪 2024-12-11 22:23:28

创建于:{
类型:日期,
默认值:当前日期
}
添加这个简单的行作为当前日期和时间

输出:-----
2021 年 7 月 2 日星期五 10:45:26 GMT+0530(印度标准时间)

created_at:{
type:Date,
default:Date.now
}
add this simple line for current date and time

output:-----
Fri Jul 02 2021 10:45:26 GMT+0530 (India Standard Time)

时间你老了 2024-12-11 22:23:28

我倾向于做的是,在架构中,我使用 Date 类型定义日期:

const exampleSchema = new mongoose.Schema({
    startDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    },
    endDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    },
    whateverDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    }
});

然后我为 mongoose 架构定义一个实例方法:

// Returns a date in 'yyyy-MM-dd' format
exampleSchema.methods.formatDate = function(datePropery) {
    const newDate = new Date(this[dateProperty]);
    let formattedDate = `${ newDate.getFullYear() }-`;
        formattedDate += `${ `0${ newDate.getMonth() + 1 }`.slice(-2) }-`;  // for double digit month
        formattedDate += `${ `0${ newDate.getDate() }`.slice(-2) }`;        // for double digit day
    return formattedDate;
}

并且,定义 mongoose 模型:

const Example = new mongoose.model('Example', exampleSchema);

稍后,在我完成之后选择了一个特定的实例(对我来说,这通常在异步函数内),例如

const item = await Example.findOne({searchFor: searchTerm});

我可以通过以下方式获取格式化日期:

item.formatDate('startDate');     // for startDate field (see exampleSchema), or
item.formatDate('endDate');       // for endDate field (see exampleSchema), or
item.formatDate('whateverDate');  // for whateverDate field (see exampleSchema).

如果该项目从Express传递到HTML,例如:

res.render('mypage', {item});

它可以用于HTML(至少对于 ejs 视图引擎的情况)为:

<%= item.formatDate('startDate') %>
<%= item.formatDate('endDate') %>
<%= item.formatDate('whateverDate') %>

也许这有点啰嗦,尽管它对我来说效果很好。

What I tend to do is, in the Schema, I define dates with a Date type:

const exampleSchema = new mongoose.Schema({
    startDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    },
    endDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    },
    whateverDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    }
});

Then I define an instance method for the mongoose schema:

// Returns a date in 'yyyy-MM-dd' format
exampleSchema.methods.formatDate = function(datePropery) {
    const newDate = new Date(this[dateProperty]);
    let formattedDate = `${ newDate.getFullYear() }-`;
        formattedDate += `${ `0${ newDate.getMonth() + 1 }`.slice(-2) }-`;  // for double digit month
        formattedDate += `${ `0${ newDate.getDate() }`.slice(-2) }`;        // for double digit day
    return formattedDate;
}

And, define the mongoose model:

const Example = new mongoose.model('Example', exampleSchema);

Later, after I've selected a particular instance (for me this is generally within an async function), e.g.

const item = await Example.findOne({searchFor: searchTerm});

I can get the formatted dates in the following way:

item.formatDate('startDate');     // for startDate field (see exampleSchema), or
item.formatDate('endDate');       // for endDate field (see exampleSchema), or
item.formatDate('whateverDate');  // for whateverDate field (see exampleSchema).

If the item is passed from Express to HTML, e.g.:

res.render('mypage', {item});

it can then be used in HTML (at least for the case of ejs view engine) as:

<%= item.formatDate('startDate') %>
<%= item.formatDate('endDate') %>
<%= item.formatDate('whateverDate') %>

Perhaps this is a bit long-winded, although it works nicely for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文