Incorrect Date Returned by Sequelize (-1 Day Difference)

My issue revolves around the birthdate field in one of my tables, which has a Data Type of Date. However, when attempting to export the data through an Express app, the date is transformed into a day earlier than it should be. For instance, a birthdate of 6/20/1978 becomes 6/19/1978 upon export.

I observed that even though the field only contains dates, something (possibly Sequelize) adds timestamps to them. If I refrain from formatting the date, it appears correctly but isn't human-readable for our exports.

The application functions flawlessly on my development notebook, but issues arise when deployed to QA as incorrect dates are returned.

Interestingly, when accessing PG3Admin on my notebook (in the Pacific timezone) to query data from the QA/Production server (located in the Hawaiian timezone), the data appears accurate.

My setup involves Sequelize v3.4.1 connected to a Postgres 9.3 database. Additionally, in my Sequelize config file, I've specified the "timezone": "-10:00" option.

Answer №1

It is recommended to use the DATEONLY datatype in sequelize for storing dates, and utilize DATE for timestamps.

As per information from this source on Github

_applyTimezone(date, options) {
  if (options.timezone) {
    if (momentTz.tz.zone(options.timezone)) {
      return momentTz(date).tz(options.timezone);
    }
    return (date = moment(date).utcOffset(options.timezone)); <-- this will convert your date to UTC
  }
  return momentTz(date);
}

Ensure to set your timezone in the sequelize configuration. For birthdays, using the DATEONLY datatype would be more suitable.

Therefore, your model could look like:

birthday: {
  type: DataTypes.DATEONLY
},
createdAt: {
  type: DataTypes.DATE
},
updatedAt: {
  type: DataTypes.DATE
}

You can find all datatypes listed in the documentation.

Answer №2

Although there may be other solutions out there, this method proved effective for me:

Customize.YOURDIALECT.DATEONLY.parser = function(input) {
    return moment(moment(input).format('YYYY-MM-DD'), "YYYY-MM-DD").add(1, 'days');
};

I trust that this tip could benefit fellow developers.

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

The function socket.on(..) is not being triggered

Currently, I am in the process of developing a straightforward website to showcase socket communication and chat capabilities. The server side is coded using Python Flask app, while the client-side utilizes JavaScript. Below is an excerpt from the server c ...

Avoid unnecessary re-renders in ReactJS Material UI tabs when pressing the "Enter

I've created a user interface with tabs using material-ui in reactJS. The issue I'm facing is that every time a tab is selected, the content under that tab reloads, causing performance problems because there's an iFrame displayed in one of t ...

Use router.get in order to pass both JSON data and an image from the Node.js back end to the React frontend

Having trouble sending both an image and JSON data to the front end from my node.js back end. I can successfully send them separately using router.get, but struggling to send them together in a single request. To send just the image, I used the code below ...

Can an image map area be identified using radial coordinates?

While I have experience with online Imagemap Generators for rectangular or circular areas in HTML pages, things get a bit tricky when dealing with pie-shaped sections. When trying to make each pie slice a separate area, the image map code generated by thes ...

Is there a way to send a response upon completion of a for loop in Node.js Express?

Within my node.js express server, I have an api function where I perform async operations using a for-of loop. controller.js const importRecords = async(req,res) => { for (const bid of distinctArr) { // executing 3 async operations for each ...

Creating an event on the containing element

Here is my HTML tag: <ul> <li> <form>...</form> <div> <div class="A"></div> <div class="B"><img class="wantToShow"></div> </div> ...

When using JavaScript to style.display = "block", the Bootstrap-4 column layout may experience a display break

My div is initially displaying properly in one row at the beginning. However, when the user changes the select option to "b" and then back to "a," the display breaks. The two texts "my left side text" and "my right text" are displayed on two lines, one be ...

Error: Angular is encountering an issue with accessing the property 'push' as it is currently undefined

I have successfully created a news ticker that works well in my codepen example. However, I am encountering an issue with integrating it into my code structure. The error message I am currently receiving is: Cannot read property 'push' of undefi ...

I am looking to enhance the readability of my asynchronous function calls

At the moment, I am handling my Promises by calling an async function and then chaining it with .then(). But I feel like there could be a more readable approach. This is how it currently works: const fetchData = async() => { const response = await ax ...

"The authentication scheme is unrecognized" - this is the message produced by Node-LinkedIn module

I am currently utilizing the node-linkedin npm package to authenticate and retrieve information about other users, such as their name, job title, company name, profile picture, and shared connections. While I am able to successfully receive and store the a ...

Ways to effectively utilize jQuery objects as arguments in the delegate function

When working with delegate and multiple selectors, you can use the following syntax: $(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla }); In projects where managing DOM elements is important, stori ...

Error: The variable 'err' is undefined in the mongoose mongodb code

Every time I try to execute this code, an error pops up stating that err is undefined Below is the code snippet causing the issue: app.post('/tinder/cards', (req, res) => { const dbCard = req.body; Cards.create(dbCard, (err, data) => { ...

Combining React-Redux and Bootstrap: A sophisticated modal feature

Struggling with the distinction between components and containers when using Bootstrap's modal in React-Redux. Instead of repetitively creating modals, I aim to develop a React Component that encompasses a modal template. For clarification, here&apo ...

Hide the address bar in a Google Maps iFrame

After numerous attempts, I still can't seem to hide the address bar on this Google Maps iFrame. Can anyone provide a solution or workaround for this issue? https://i.sstatic.net/x0pl9.png I have tried using display:none; in our CSS, which successfull ...

Fundamental Guidelines for Firebase

I've recently started working with Firebase and I'm encountering some issues with the security rules. My project is a blog website where visitors can read posts, users, and comments without being logged in. However, logged-in and verified users ...

Dynamic Route Parameters in Express 4: Learn how to capture parameters in a route structured to mimic a file name format

Currently, I am working on implementing an Express 4 route endpoint that includes part of the route in the file URL section, specifically the file name. This setup is crucial for dynamically generated images. Allow me to illustrate this with an example... ...

How to use getServerSideProps in Next.js

In my current scenario, I find myself within a folder in the pages directory, specifically in a file named [id].jsx. My goal is to make getServerSideProps return just the name of the page, for example /page/id123 should return id123. import Link from &a ...

Vue.js: click event does not trigger transform animation

I am facing a challenge with rotating an arrow icon within a dropdown menu. Despite my efforts, the rotation does not synchronize with the appearance of the dropdown menu. Here is the Vue component code snippet: <nav> <section class= ...

Connecting AngularJS with select options

I am currently developing a checkout feature that calculates shipping prices based on the selected country. If the user picks United States, it should display US. For any other country selection, it should show Not US While the shipping function correctly ...

Utilizing a React component within an Express server: A comprehensive guide

I need to create a way for users to upload files to my express backend, but the form is within a react component. How can I incorporate my react ConverterSec2 component into the get function? server.js: import ConverterSec2 from "./ihertz_website/src ...