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

AFA*_*FAF 1 schema date mongodb reactjs

我正在使用 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);
Run Code Online (Sandbox Code Playgroud)

我的反应代码:

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

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

        </h1>

     </div>
  </header>
[...]
Run Code Online (Sandbox Code Playgroud)

GJK*_*GJK 6

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

moment(this.state.project.created).format('YYYY-mm-dd')
Run Code Online (Sandbox Code Playgroud)

如果不想引入第三方库,可以使用内置的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}`;
}
Run Code Online (Sandbox Code Playgroud)