【发布时间】:2020-06-11 08:43:22
【问题描述】:
我在 TypeScript Node 中创建了一个与 typescript react 前端通信的后端。用户的模型模式是使用 Mongoose 创建的,每个用户都有一个:
- 名字
- 姓氏
- 电子邮件
- 出生日期
- 创建时间
我需要将日期格式更改为“DD-MM-YYYY”,以便在更新/编辑用户时自动读取默认值。
后端
user.ts
import * as mongoose from 'mongoose';
interface IUser {
_id: string;
firstName: string;
lastName: string;
email: string;
dob: Date; // Date of Birth
created: Date;
}
const UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
dob: Date, // Date of Birth
created: Date,
});
const UserModel = mongoose.model('User', UserSchema);
export { UserModel, IUser }
前端
Edit.tsx
<div className="form-group col-md-12">
<label htmlFor="dob"> Date of Birth </label>
<input
type="date"
id="dob"
defaultValue={moment(this.state.user.dob).format("DD-MM-YYYY")}
onChange={(e) => this.handleInputChanges(e)}
name="dob"
className="form-control"
placeholder="Enter customer's date of birth"
/>
</div>
当我尝试更新它时,前面显示了用户的所有信息,因为格式错误。
它使用“2020-02-26T10:22:19.018Z” 它需要使用:“26-02-2020”
【问题讨论】:
-
你想要什么?请简述。
-
我假设
defaultValue必须是Date对象,因此请尝试defaultValue={moment(this.state.user.dob).toDate()}。为了改变格式看看stackoverflow.com/questions/7372038/…也许你必须使用其中之一:hongkiat.com/blog/… -
我想在更新用户时将日期格式更改为在 html 输入字段的默认值内可用
-
所以我尝试使用moment js但没有运气:
defaultValue={moment(this.state.user.dob).format('DD-MM-YYYY')}我设置了这样的默认值,并像输入字段建议的那样格式化日期。有人知道我错过了什么吗?
标签: node.js reactjs mongodb typescript mongoose