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

标签 mongodb reactjs date schema

我正在使用 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/

相关文章:

mongodb - Grails + Mongodb =不持久化对象。为什么?

php - 在 PHP Phalcon 框架中使用 MongoDb

javascript - 接下来如何在react SSR框架中使用TS+css+scss?

java - 使用 Calender 或 java 中的任何类查找上个月名称

php - 使用 PHP 的 DateTime 警告

java日期格式化程序不会将正常小时格式更改为24小时格式

mongodb - 在 mongodb 中跨副本分发读取

ruby-on-rails - Rails 模型单一化无法正常工作

reactjs - componentWillReceiveProps 已重命名

javascript - ReactJs 在按钮单击时更改文本问题