首页 > 解决方案 > 如何格式化从后端获得的日期

问题描述

createdDate我为每个需要在表中创建和显示但无法更改的新人放入了我的猫鼬模式,所以我在猫鼬模式中做了。但是,当我在前端获取日期并将其放入表中时,我首先映射。js 元素中的所有项目,当我在其他文件中调用我的表与 props.date 中的日期时,我无法格式化我的日期,无法像 dd/MM/yyyy 或任何类似的东西,而是我喜欢2020-11-13T12:37:05.637Z。有人可以帮助我如何格式化我从道具和数据库中获得的日期。

这是我从道具中调用日期的地方。

return (
    <React.Fragment>
      {error && <Errormsg error={error} />}
      <tbody className="table">
        <tr>
          <td>{props.id}</td>
          <td>{props.name}</td>
          <td>{props.surname}</td>
          <td>{props.city}</td>
          <td>{props.address}</td>
          <td>{props.phone}</td>
          <td>{props.date}</td>
          <td>
            <Button>
              <Link to={`/person/${props.id}`}>Edit</Link>
            </Button>
            <Button onClick={deleteHandler}>Delete</Button>
          </td>
        </tr>
      </tbody>
    </React.Fragment>
  );
};

一旦我从后端得到它,这就是我映射它的地方。

  return (
    <table className="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>NAME</th>
          <th>SURNAME</th>
          <th>CITY</th>
          <th>ADDRESS</th>
          <th>PHONE</th>
          <th>CREATED DATE</th>
          <th>ACTION</th>
        </tr>
      </thead>
      {props.items.map((person) => (
        <PersonItems
          key={person.id}
          id={person.id}
          name={person.name}
          surname={person.surname}
          city={person.city}
          address={person.address}
          phone={person.phone}
          date={person.createdDate}
          onDelete={props.onDeletePerson}
        />
      ))}
         </table>
  );
};

这是我的模式。

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const personSchema = new Schema({
  name: { type: String, required: true },
  surname: { type: String, required: true },
  city: { type: String, required: true },
  address: { type: String, required: true },
  phone: { type: Number, required: true },
  createdDate: { type: Date, default: Date.now}
});

module.exports = mongoose.model("Persons", personSchema);

标签: javascriptnode.jsreactjsmongodbmongoose

解决方案


尝试new Date('2020-11-13T12:37:05.637Z').toLocaleString()输出会像11/13/2020, 2:37:05 PM

如果您使用然后拆分功能,new Date('2020-11-13T12:37:05.637Z').toLocaleString().split(',')[0]您将得到11/13/2020我所理解的您所需要的

如果你想为它使用另一个包,你绝对应该使用 moment.js


推荐阅读