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;
};
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