0

I am trying to fetch data where the createdAt field falls between a date range with a timezone specified. This is what I have so far but this is not returning the correct data in the specified date range and timezone. An example of what a createdAt value in the database looks like is

2022-06-14 02:37:16.236+00

let timezone = req.header('Timezone')
if (!timezone || !moment.tz.zone(timezone)) {
    timezone = moment.tz.guess();
}

const startOfDay = moment(date).tz(timezone).startOf('day')
const endOfDay = moment(startOfDay).endOf('day')

// Fetch all completed events within the date range
const events = await models.Event.findAll({
    attributes: [
      'id',
      'accuracy',
    ],
    where: {
      status: 'completed',
      createdAt: {
        [Op.between]: [startOfDay, endOfDay],
      },
    },
    order: [['createdAt', 'ASC']],
    raw: true,
  })

2 Answers 2

1

You have to format moment dates to any acceptable date and time with the timezone format of PostgreSQL. For example,

startOfDay.format("YYYY-MM-DD HH:mm:ss z")

So the code should be like this:

let timezone = req.header('Timezone')
if (!timezone || !moment.tz.zone(timezone)) {
    timezone = moment.tz.guess();
}

const startOfDay = moment(date).tz(timezone).startOf('day').format("YYYY-MM-DD HH:mm:ss z")
const endOfDay = moment(startOfDay).endOf('day').format("YYYY-MM-DD HH:mm:ss z")

// Fetch all completed events within the date range
const events = await models.Event.findAll({
    attributes: [
      'id',
      'accuracy',
    ],
    where: {
      status: 'completed',
      createdAt: {
        [Op.between]: [startOfDay, endOfDay],
      },
    },
    order: [['createdAt', 'ASC']],
    raw: true,
  })
Sign up to request clarification or add additional context in comments.

Comments

0

For sequelize raw query mysql you should use

moment(your_time).format('YYYY-MM-DDTHH:mm:ssZ');

This will clear the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.