Home > OS >  Edit the createdDate in mongoose
Edit the createdDate in mongoose

Time:03-04

So I have a notice section on my site which displays what date the notice was created. When showing the createdAt date it displays like this -

Thu Mar 03 2022 15:11:22 GMT 0000 (Greenwich Mean Time)

Instead I would like it display as

03/03/2022 - 15:11

Thats DD/MM/YEAR.

Here is my Schema and my EJS that I am displaying it with. Also how it is stored in the database.

Schema

const noticeSchema = new mongoose.Schema({
noticeTitle: {
    type: String,
    required: true
},
noticeText: {
    type: String,
    required: true
},
author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
}
}, {timestamps: true 
}); 

EJS

<% notices.map(notice => notices.createdAt ) %>
<%= notice.createdAt %>

Database Entry

_id: new ObjectId("6220ead4f238fc30822e5e6d"),
noticeTitle: 'test3',
noticeText: '<p>test3</p>',
author: {
  _id: new ObjectId("621e06a6c29dc2273e412537"),
  firstName: 'test',
  lastName: 'test',
  jobRole: 'Other',
  email: 'test',
  username: 'DeneHCAdmin',
  __v: 0
},
createdAt: 2022-03-03T16:20:36.680Z,
updatedAt: 2022-03-03T16:20:36.680Z,
__v: 0
}

Can anybody help?

CodePudding user response:

It's as easy as splitting the Date into several constants and connecting them together

const creationDate = new Date(),
  dateYear = creationDate.getFullYear(),
  dateMonth = creationDate.getMonth(),
  dateDay = creationDate.getDay(),
  dateHour = creationDate.getHours(),
  dateMinute = creationDate.getMinutes();

const dateFullTime = `${dateMonth}/${dateDay}/${dateYear} - ${dateHour}:${dateMinute}`

console.log(dateFullTime)
// expected output dd/mm/yyyy - hh:hh (if you'd want a zero before the month and day when it's only one character, you would have to make an easy if statement.)

CodePudding user response:

const t = new Date();
const date = t.getDate();
const month = t.getMonth();
const year = t.getFullYear();
const hours = t.getHours();
const minutes = t.getMinutes();
const time = `${date}/${month}/${year} - ${hours}:${minutes}`;

It is just simple date manipulation in javascript, doesn't have anything to do with mongoose itself

  • Related