-1

How to get record if createdDate is from one year later using sequelize

userId createdDate
1.      2023-07-19 00:49:59
2.      2022-08-20 00:49:59

Tried

 return this.findAll({
       createdDate: {
        [Op.gte]: new Date(new Date().getFullYear(), 1)
       }
    });

Expected Record
2.      2022-08-20 00:49:59

2 Answers2

0
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);
0

from this: https://stackoverflow.com/a/33070496/15557206

you can get date + 1 full year with:

const aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
console.log(aYearFromNow);