0

I have created a backend in TypeScript Node that communicates with a typescript react frontend. The model schemas for users are created with Mongoose and each user have a:

  • First Name
  • Last Name
  • email
  • Date of Birth
  • Creation time

I need to change the format of the date to "DD-MM-YYYY" so it can be automatically read in a defaultValue when a user is updated/edited.

Backend

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 }

Frontend

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>

The front show all the information of the user when I try to update it expect for the Date because the format is wrong.

It uses "2020-02-26T10:22:19.018Z" It needs to use: "26-02-2020"

Community
  • 1
  • 1
Frederik Bruun
  • 27
  • 2
  • 11
  • What you want? Please express briefly. – Ashish Feb 27 '20 at 10:51
  • I assume `defaultValue` must be a `Date` object, thus try `defaultValue={moment(this.state.user.dob).toDate()} `. In order to change to format have a look at https://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format Perhaps you have to use one of these: https://www.hongkiat.com/blog/useful-calendar-date-picker-scripts-for-web-developers/ – Wernfried Domscheit Feb 27 '20 at 11:08
  • I want to change Date format to it is usable within the default value of html input field when updating a user – Frederik Bruun Feb 27 '20 at 11:11
  • So I have tried using moment js with no luck: ```defaultValue={moment(this.state.user.dob).format('DD-MM-YYYY')}``` I set the default value like this and format the date like the input field suggests. Anyone has any clues what I am missing? – Frederik Bruun Feb 27 '20 at 11:51

1 Answers1

0

Try this

db.getCollection('test').aggregate(
[
     {
       $project: {
           newDate: {
              $dateToString: {
                format: '%d-%m-%Y',
                date: '$date'
              }
            }

       }
   }
]
)
Shantanu Madane
  • 617
  • 5
  • 14