node.jssequelize.jsluxon

Sequelize is saving dates in the incorrect time zone


I am passing dates from the front-end to the back-end and then saving them in to the database using sequelize. The dates that are comming from the front-end are local to the users. The first problem accurs when I try to read the date from the front-end, in the back-end (nodejs), the date appears in the wrong time zone (-3h) from that date that came. I solve that with luxon and set it to the date it should be that came from the front-end. Then when I save it to the database, it again becomes in the wrong time zone when I check it in the database (mysql). I am later send dates to the front-end, so they must be in the correct timezone. How can I save dates in the correct timezones? The code:

module.exports.create_meal_post = async (req, res) => {
  const { prods, createdAt, ...rest } = req.body;
  const luxonDate = DateTime.fromISO(createdAt);
  const normalizedDate = luxonDate.toISO();
  console.log("from-front-end : ", createdAt); // incorrect date (-3h)
  console.log("luxon date: ", normalizedDate); // correct date
  try {
    const result = await sequelize.transaction(async (t) => {
      const meal = await Meals.create(
        {
          ...rest,
          createdAt: normalizedDate,
          user_id: req.token.userId,
        },
        { transaction: t }
      );
      const meal_id = meal.meal_id;
      const products = prods.map((obj) => {
        return {
          meal_id: meal_id,
          user_id: req.token.userId,
          product_id: obj.product_id,
          createdAt: normalizedDate,
          ...obj,
        };
      });
      await MealProducts.bulkCreate(products, { transaction: t });
      return meal;
    });
    res.status(201).send(result);
  } catch (error) {
    console.log(error);
    res.status(400).json(error);
  }
};

I have also tryed to achieve this with a setter, the result is the same. Logged results:

from-front-end : 2023-08-02T18:08:14.496Z luxon date: 2023-08-02T21:08:14.496+03:00 Saved date in the database: 2023-08-02 18:08:14


Solution

  • The way I worked around this problem is that I stored my date as string, by using luxon I extracted the string and converted them to dates.

    Date attribute in the model:

    createdAt: {
        type: DataTypes.STRING,
        allowNull: false,
      },
    

    I saved it as ISO and then on getting the dates I converted the strings to ISO dates again. That was done with luxon js