gpt4 book ai didi

mongodb - ReactJS - 如何从 MongoDB Date.now 更改日期格式

转载 作者:行者123 更新时间:2023-12-02 00:28:49 27 4
gpt4 key购买 nike

我正在使用 MongoDB 和 ReactJS。

所以我希望用户可以在创建新项目时看到,但 mongodb 显示此日期格式“2018-10-08 18:09:56.628”,而我只想显示“2018-10-08”。我能做什么?

我的项目架构:

let mongoose = require("mongoose");

let projectSchema = new mongoose.Schema({

projectname: String,
typeofproject: String,
imageURL: String,
dateMonthFrom: String,
dateYearFrom: String,
dateMonthTo: String,
dateYearTo: String,
tasks: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tasks'
}],
user: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
created: {
type:Date,
default: Date.now
}
})

module.exports = mongoose.model('Project', projectSchema);

我的 React 代码:

[...]
<header>
<div>
<h1>

{this.state.project.projectname} // "Title"
{this.state.project.created} // "2018-10-08 18:09:56.628"

</h1>

</div>
</header>
[...]

最佳答案

您需要使用某种格式化功能。您可以使用内置的 Date 函数编写自己的函数,但是像 moment 这样的库(可能还有 moment-timezone )让它变得非常简单。

moment(this.state.project.created).format('YYYY-mm-dd')

如果您不想引入第三方库,您可以使用内置的 Date函数并编写您自己的方法。

function formatDate(date) {
const currentMonth = date.getMonth();
const monthString = currentMonth >= 10 ? currentMonth : `0${currentMonth}`;
const currentDate = date.getDate();
const dateString = currentDate >= 10 ? currentDate : `0${currentDate}`;
return `${date.getFullYear()}-${monthString}-${currentDate}`;
}

关于mongodb - ReactJS - 如何从 MongoDB Date.now 更改日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52707425/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com