Search code examples
htmldatetimemongoose-schema

The simplest way to convert a long date format to YY/MM/DD HTML


I'm new in web development.

my problem is: how to disaply in html a date in simple format dd/mm/yy instead of Fri Sep 01 2000 00:00:00 GMT+0300 (Israel Daylight Time)

I'm trying to create a crud api using mongoose.

I have a schema model, one of the fileds is a filed of type date:

joinDate: {type: Date, required: true}

in the controller: post- program.joinDate= req.body.joinDate; get-

Program.find((err, docs) => {
    res.render("program/list", {
        list: docs
    });
});

in the view: <td>{{this.joinDate}}</td>

My question: The easy and fast way to convert the long format to short and cleraly format. I saw some solutions but I think they are too complex and outdated.

If you have any idea for me I would be happy:) thank's you!


Solution

  • I often use mongoose virtual + moments for this.

    eventSchema.virtual('joinDate_formatted').get(function () {
    
    return moment(joinDate).calendar({
      sameDay: 'h:mm A',
      nextDay: '[Tomorrow] h:mm A',
      nextWeek: 'dddd',
      lastDay: '[Yesterday] h:mm A',
      lastWeek: '[Last] dddd',
      sameElse: 'DD/MM/YYYY h:mm A'
    
    }); //Above shows in calendar format but u can do whatever u want in moment
    });
    

    When u do any find on the collection, you will get a joinDate_formatted which u can use on your front end.