Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

284
Views
Sequelize format date

I have 2 tables Posts and Likes.

and Posts table associated to Likes table by hasMany.

I'm trying to select all the posts and include the likes that belongs to it.

The Question is how to format the datetime or (createdAt).

I use NodeJS, ExpressJS, Sequelize and MySQL.

Thanks in advance.

Get posts function:

router.get("/", validateToken, async (req, res) => {
  const listOfPosts = await Posts.findAll({
    include: [Likes],
    order: [["createdAt", "desc"]],
  });

  const likedPosts = await Likes.findAll({ where: { UserId: req.user.id } });
  res.json({ listOfPosts: listOfPosts, likedPosts: likedPosts });
});

Posts Model:

module.exports = (sequelize, DataTypes) => {
  const Posts = sequelize.define("Posts", {
    title: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    postText: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    username: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  });

  Posts.associate = (models) => {
    Posts.hasMany(models.Comments, {
      onDelete: "cascade",
    });

    Posts.hasMany(models.Likes, {
      onDelete: "cascade",
    });
  };

  return Posts;
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

createdAt parameter is accepted by Node.js as a regular Date instance. You can retrieve parts or the date to build format as you wish.

let date = post.createdAt;

let day = date.getDate().toString().padStart(2, '0')
let month = (date.getMonth()+1).toString().padStart(2, '0')
let year = date.getFullYear().toString()

let hours = date.getHours().toString().padStart(2, '0')
let minutes = date.getMinutes().toString().padStart(2, '0')


let dateFormatted = `${day}.${month}.${year} ${hours}:${minutes}`;

console.log(dateFormatted);

padStart is used to have one heading zero if number has only one digit, like here: 01.05.2022. The same for hours and minutes, you can remove it as you wish. Month is increased by 1, because January is 0, so to be readable for user, we need to increment it.

Better practice is to move date formatting to function

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!