我在我的mongoose模式中为每个需要创建并显示在表中的新人添加了createdDate,但是不能更改,所以我在mongoose模式中这样做了。但是,当我把日期放在表的前端,我首先地图。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);
您可以使用momentjs来实现这一点
为了得到你想要的结果,你可以这样使用它
<td>{moment(props.date).format("DD/MM/YYYY")}</td>
只需将上面的行添加到您想要以这种格式显示日期的任何地方。
尝试新日期('2020-11-13t12:37:05.637z').toLocaleString()
输出将类似于11/13/2020,2:37:05pm
如果您使用类似new Date('2020-11-13t12:37:05.637z').tolocaleString().split(',')[0]
这样的拆分函数,您将得到11/13/2020
,我所理解的就是您需要的
如果您想为它使用另一个包,那么您绝对应该使用moment.js。
{Moment("Your date").format("DD/MM/YYYY")}
示例代码-https://codesandbox.io/s/trusting-antonelli-4r1qw?file=/src/app.js:200-257