const { Op } = require('sequelize');
// Assuming your model is named 'YourModel'
const YourModel = require('./path/to/your/model');
// Get the current date
const currentDate = new Date();
// Calculate the date exactly one year ago from the current date
const oneYearAgo = new Date(currentDate.getFullYear() - 1, currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds());
// Perform the query
return YourModel.findAll({
where: {
createdDate: {
[Op.gte]: oneYearAgo,
[Op.lt]: currentDate,
},
},
});
You calculate the oneYearAgo
date by subtracting one year from the current date's year and keeping the same month, day, hours, minutes, and seconds. Then, we use the Op.gte
operator to find records greater than or equal to oneYearAgo, and the Op.lt
operator to find records less than currentDate
. This way, we retrieve records with a createdDate
falling within the last one year.
EDIT based on question:
should subtract 1 year from the current date.
// Get the current date
const currentDate = new Date();
// Calculate the date exactly one year ago from the current date
const oneYearAgo = new Date(currentDate);
oneYearAgo.setFullYear(currentDate.getFullYear() - 1);
console.log(oneYearAgo);