Comparing dates in Sequelize with date timestamps

My issue arises when I pass a date and attempt to compare it with the default createdAt column.

where: {
                createdAt: {
                    $eq: date
                }
            }

The date I am using is in string format like this: date = '2018-12-12'

The problem lies in Sequelize not just comparing the date, but also adding the time 00:00:00 to my date before comparing. This results in Sequelize generating a query like this:

WHERE `redeem_points`.`createdAt` = '2018-11-02 00:00:00';

What I'm looking for

WHERE `redeem_points`.`createdAt` = '2018-11-02';

Is there a way to achieve this using Sequelize?

Answer №1

Perhaps a more suitable approach could be:

{
  where: {
    createdOn: { [Op.like]: `${selectedDate}%`, },
  }
}

This would result in SQL syntax similar to the following (please note the wildcard):

WHERE createdOn LIKE '2022-07-15%'

You can explore different Operators to access a wide array of SQL syntax equivalents. Furthermore, it seems that the shorthand you are currently employing may be outdated, so I have replaced it with the correct Op syntax. If you are not utilizing variable destructuring, you might require sequelize.Op.

Answer №2

To accomplish this task, you can simply follow the code snippet below:

createdAt:{[Op.between]:[moment().startOf("day").toDate(),moment().endOd("day").toDate()]}

Answer №3

Using the moment.js library to manipulate dates and times can be helpful, but it is also possible to achieve the same result with native JavaScript functionality while considering timezones.

let filter = {};

// To retrieve data for a specific date
// if (date) {
//   filter.createdAt = {
//     [Op.and]: [
//       {
//         [Op.gte]: new Date(moment(date).startOf('day').format()),
//       },
//       {
//         [Op.lte]: new Date(moment(date).endOf('day').format()),
//       },
//     ],
//   };
// }

// If you want data for the current day
filter.createdAt = {
  [Op.and]: [
    {
      [Op.gte]: moment().startOf('day').toDate(),
    },
    {
      [Op.lte]: moment().endOf('day').toDate(),
    },
  ],
};

ActivityLog.findAll({
  where: filter,
});

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

Creating a Authentic Screw Top Appearance with CSS

I am striving to create a realistic screw head. Here is what I have done so far: <div class="screw"><div class="indent"></div></div> .screw { position: absolute; top: 10px; left: 49%; width: 30px; height: 30px ...

What is the best way to include several IDs in a discord.js verification process?

I am attempting to create a basic script that verifies if the user's ID matches the one specified in the code. However, I'm struggling to understand how to achieve this. Any assistance from you all would be greatly appreciated. if(message.autho ...

Emphasize text within the input field

Is there a way to create an input textarea that can detect words from an array in this.state and highlight those words as the user types text? Here is what I'm aiming for: The list of words: https://i.sstatic.net/eOx7G.png The input textarea examp ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Exploring the best practices: Defining schemas and models in Express.js with MongoDB

I'm currently developing an app using express and mongodb. The app.js file has become quite extensive as it contains all the schemas, models, and routes. I am seeking advice on how to organize my code better by defining the schemas and models in separ ...

Navigating in React Navigation: Techniques to Directly Access a Specific Index in a Datasource

I am a beginner at React Native and I have been working on developing a simple recipe app. Everything was going well until I reached the point where I needed to navigate to a specific recipe from my dataset. I am looking to create a singleRecipe.js compone ...

Displaying a concealed form or Unveiling a popup dialog

What is the most effective way to display a simple form on an HTML page with a save button that calls a web method? I'm currently contemplating between the following options: Reveal a hidden <div> containing a form with the same functionality ...

Unable to display icon using the fontawesome react-js library

import "./App.css"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' function App() { return ( <div className="container"> <input type="text" className="form-control" placeholder ...

Tips for incorporating JavaScript code into back4app.com using Objective-C:1. Start by accessing the

Currently, I am trying to retrieve "ServerDate" from back4app.com using PFCloud. Unfortunately, I have encountered the following issue: Invalid function: "getServerDate" (Code: 141, Version: 1.13.0) When I attempted to use the code below: [PFCloud ...

Customize the width of a DataTable cell in VuetifyJS

I am currently utilizing the VuetifyJS Data Table and I'm looking for a way to reduce the spacing between the entries in each header cell. Adding a width to each header did not achieve the desired result, as it seems there is a minimum predefined widt ...

Tips for retrieving the value when a button is clicked in AngularJS

Looking for assistance on retrieving the selected value in AngularJS when a button is clicked. Below is the code I am currently using: <div class="form-inline"> <div class="form-group"> <select class="form-control" data-n ...

Arrange the array of items according to the order specified in a separate array

Related Questions: JavaScript - Sorting an array based on another array of integers Sort an array in JavaScript based on another array If I come across an array structured like this: ['one', 'four', 'two'] And then ...

Utilize the automatically generated objectId or generate a custom Unique ID to map classes within Parse

We are looking to upload a large amount of data to our mobile backend on Parse. Our data consists of two classes - Store and Product. A store can have multiple products, while each product belongs to only one store. We want to streamline this process by bu ...

Icon-enhanced Bootstrap dropdown selection

I have a unique select dropdown using Bootstrap where I want to display icons like the example below: https://i.sstatic.net/dZmTS.png <!DOCTYPE html> <html> <head> <script src="/scripts/snippet-javascript-console.min.js?v=1"& ...

modifying the click state using a variable in jquery

Something feels off about my approach to this task. I currently have a series of hyperlinks, and when they are clicked, they go through a short sequence before changing states. When clicked again, they revert to their original state. var favourites = fun ...

Issue with vue-router redirection when pushing a route

I have set up my router configuration as follows: const router = new Router({ mode: 'history', routes: [ // root { path: '/', component: ComponentPage, redirect: routePrefix.public, children: [ ...

Get rid of any type of encoding or default encoding that may be applied to a jQuery ajax call

Is it possible to completely remove all types of encoding, including default encoding, on a jQuery AJAX call? Here is an example JavaScript code: function callServer() { debugger; var uncompressed64Data = "/9j/4AAQSkZJRgABAQEAYABgAAD/2 ...

Is it possible to dynamically assign class properties from an array in JavaScript/TypeScript?

Greetings for the assistance in advance. Currently, I am working with TypeScript, but I believe any JS solution will suffice. I aim to create something akin to the following: class ExcelData { 'Id 1': items[0].id, 'Quantity 1': item ...

Is there a method in Grails to locate an entry by the highest id and

I've searched extensively for solutions to my question on various platforms, including SO, but have only come across cases where people are looking for the highest id, max dateCreated, or latest db entry. However, what I need is to retrieve the most r ...

Displaying both the label and store ID in Jquery autocomplete data

I have implemented jQuery UI autocomplete with an AJAX source on my input field. The goal is to display the label to the user, while storing the corresponding ID in the value behind the scenes without using a hidden field. I aim to achieve this by storing ...