Sequelize is providing a date that is earlier than the one initially received

Hello everyone, I'm facing an issue with Sequelize where it seems to be returning the date from the backend as the day before the actual date passed. Additionally, it is adding a default time of 23:00:00. To elaborate, when a date is selected in the frontend using a datepicker and sent to the backend, it appears correctly in the Backend console. However, when used in a where clause, it shows the previous day's date along with the time stamp. For example, if the date chosen is 2020-07-11, the where clause displays 2020-07-10 23:00:00 +00:00. Is there anyone who knows how to resolve this issue? I will share the code and a screenshot from the backend console to illustrate the problem.

https://i.stack.imgur.com/ONjP5.png

var Viagem = require('../../model/viagem');
var pedido_viagem = require('../../model/pedido_viagem');
var Estado = require('../../model/estado');
var Pessoa = require('../../model/pessoa');
var Partida = require('../../model/freguesias');
var Chegada = require('../../model/freguesias');
const sequelize = require('../../model/database');
const viagem = require('../../model/viagem');

const cmv_cont = {}
sequelize.sync()

cmv_cont.pendentes_data_inicio = async(req, res) => {
    const data_inicio_filtragem = req.query;
console.log(data_inicio_filtragem.data_inicio);
    const data = await Viagem.findAll({
            include: [{
                model: Pessoa,
                attributes: ['p_nome', 'u_nome']
            }],
            where: [
                {estado: "2"}, 
                {pago_pela_cmv: "0" },
                {data_viagem: "" + data_inicio_filtragem.data_inicio }],
            order: [
                ['data_viagem', 'ASC']
            ],

        })
        .then(function(data) {

            return data;
        })
        .catch(error => {
            console.log('Erro: ' + error);
            return error;
        });
    res.json({ success: true, data: data });

}

module.exports = cmv_cont;

Answer №1

The reason for this issue is due to the timezone configuration in sequelize.

It seems like you are located in Portugal based on your code, so the timezone is UTC+00:00. However, during Daylight Saving Time, Europe/Lisbon switches to UTC+01:00 from March 29 until October 25

Sequelize automatically saves all Datetimes as UTC+00:00

You can try running the following code snippet:

const moment = require('moment');

const date = moment('2020-07-11'); // moment("2020-07-11T00:00:00.000")
date.utc(); // moment.utc("2020-07-10T23:00:00.000+00:00")

This behavior is standard and aligns with the desired configuration. When retrieving a created Viagem, the date should be returned in your local format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Securely store files by encrypting them with Node.js before saving to the disk

At the moment, I am making use of the multer library to store files on the File system. This particular application is built using Node and Express. I currently have a process in place where I save the file on the server first and then encrypt it. After e ...

Updating Mapped Components with Selected State

One of the components in my project is a mapped component that dynamically displays API data. Each card displayed by this component receives unique props, resulting in cards that look different from one another. An example can be seen below. View Example ...

Error: Interaction has already been acknowledged. What is the solution?

Error: Issue Detected: DiscordAPIError - Interaction has already been acknowledged. at RequestHandler.execute (C:\Users\stask\Desktop\economy koshki.fun\node_modules\discord.js\src\rest\RequestHandler.js:350 ...

utilize the getStaticProps function within the specified component

I recently started a project using Next.js and TypeScript. I have a main component that is called in the index.js page, where I use the getStaticProps function. However, when I log the prop object returned by getStaticProps in my main component, it shows a ...

Encountering a problem with the navigation bar in the latest version of Next.js, version 13

"use client" import {Navbar, Button, Link, Text} from "@nextui-org/react"; import {styled} from "@nextui-org/react" const Box = styled("div", { boxSizing: "border-box", }); const AcmeLogo = () => ( ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

Search for the booking object based on the user in MongoDB

In my Next.js app, I have 2 models - Booking and User. The object below represents a booking object. When a user books some dates, a new object is created in the bookings model. On the booking details page, users should be able to see details of their book ...

What is the best way to present sorted items on a user interface?

I have a unique Med interface containing properties like drugClass, dosage, and name. Using this interface, I created an array of drugs with different attributes. How can I filter this array by drugClass and then display the filtered data on a web page? ...

What is the method by which the Material-UI Button component determines the properties for the component that is passed to the `component` prop

Could someone please clarify how Material-UI enhances the properties of its Button component by incorporating the properties of a specific component if passed in the component attribute? interface MyLinkProps extends ButtonBaseProps { someRandomProp: str ...

What is the best way to display an input label or placeholder label consistently?

I am currently utilizing the multi-select feature with checkboxes provided by Material UI v4. By default, the settings display an array of 'SELECTED' values using the renderValue={selected => selected.join(', ') function. However, I wan ...

The Redux state fails to update despite there being no difference between the old and new states

Having trouble with my Redux state. I created a reducer to update a value in an array, following immutability principles. However, the state is not updating as expected. Even added console logs to compare old and new states, but they return false. Any ide ...

Unable to modify the default threshold on Spotify API (Top Artists) in a React Native environment

I've been struggling to figure out why this code isn't working correctly. No matter what I try, it only returns 20 artists. const spotifyObj = await this.getValidSPObj(); const { id: user_id } = await spotifyObj.getMe(); const { items: popularArt ...

Can the material UI steps be modified by clicking on the stepper icons?

Does anyone know how to use Material UI stepper to allow users to navigate to a specific step by clicking on the icons? For example, if there are 5 steps and the user is on the fourth step, clicking on the icon for step 1 should take them back to step one. ...

During the deployment of a ReactJS app, webpack encounters difficulty resolving folders

While developing my ReactJS app, everything ran smoothly on localhost. However, I encountered some serious issues when I tried to deploy the app to a hosting service. In my project, I have a ./reducers folder which houses all of my reducers. Here is the s ...

Customize your Material-UI theme with a unique hover effect for contained buttons

Currently, I am in the process of setting up a theme for Material-Ui on my React application. Within the app, there are two types of buttons that I utilize - contained and outlined. The issue lies with the hover effect on the contained button (while the ou ...

Squashing the `require()` method in nwJS using emberJS

I am facing an issue with my nwjs application that connects to a web address hosting an ember application. I need to access the node context within the ember application to determine the user's operating system for updating purposes. I attempted to do ...

What is the best way to find the most commonly used category for a product in a MongoDB collection?

I've been diving into MongoDB and encountered a challenge with my current task. I'm trying to figure out how to determine the most frequently used category in a collection. According to this JSON, the most used category is CIES. My goal is to dis ...

NodeJS CORS functionality failing to function properly in the Google Chrome browser

In my nodejs script, I have implemented CORS as shown below: var express = require('express') , cors = require('cors') , app = express(); app.use(cors()); To fetch JSON data from another domain, I am using an AJAX request. While ...

Exploring files within a Node.js module using npm

I'm currently in the process of developing a Node module and I want to give users the option to optionally require some files that are part of the module. For instance: var M = require('my-module'); var Foo = require('my-module/foo&apo ...

Forest Admin's route for /forest/authentication cannot be found and is returning a 404

I am struggling to configure Forest Admin in my local environment using Express and MySQL. Whenever I attempt to authenticate, I encounter a 404 error for the /forest/authentication route. https://i.stack.imgur.com/aEXTL.png app.js const createError = re ...