How to Compare Dates in an Array of MongoDB Objects with Varied Date Formats

In the frontend, I am utilizing a datepicker that sends a date through an AJAX Request. The date is in the format 'YYYY-MM-DD'. I need to compare this date with dates in an array retrieved from a MongoDB collection. These dates include a Timezone and are formatted as follows: "2020-06-03T00:00:00.000Z"

Slot Json Object

{
  date: [
    2020-06-03T00:00:00.000Z,
    2020-06-05T00:00:00.000Z,
    2020-06-07T00:00:00.000Z
  ],
  __v: 0
}

I have to iterate over each date in the array and compare it with the date from the frontend.

Assuming the user input date is

let userInput = '2020-06-03';

I need to ensure that comparing '2020-06-03' with '2020-06-03T00:00:00.000Z' returns true. How can I achieve this comparison while looping through all elements in the array?

Answer №1

When your date array is always set to 00:00:00, I would recommend using this approach:

const dates = [
  '2020-07-12T00:00:00.000Z',
  '2020-07-15T00:00:00.000Z',
  '2020-07-18T00:00:00.000Z'
];

let userInput = '2020-07-15';

function searchDates(date) {
  const searchDate = Date.parse(date);
  const foundDates = [];

  dates.forEach(date => {
    const tempDate = Date.parse(date);

    if (tempDate === searchDate) {
      foundDates.push(date);
    }
  });

  return foundDates;
}

console.log(searchDates(userInput));

If there are other factors to take into consideration, please let me know.

Answer №2

Ensure that the date strings in the input and the array of dates are correctly formatted for parsing. Then, you can simply utilize the isSame() function to determine if the dates are identical

let input = "2020-06-03";
let arr = [
  "2020-06-03T00:00:00.000Z",
  "2020-06-05T00:00:00.000Z",
  "2020-06-07T00:00:00.000Z"
];
let result = arr.map(item =>
  moment(item, "YYYY-MM-DD hh:mm:ss zz").isSame(input, "YYYY-MM-DD")
);
console.log(result);
<script src="https://momentjs.com/downloads/moment.js"></script>

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 EJS template on the Express app is encountering an issue: it is unable to find the view "/id" within the views directory located at "/home/USER/Desktop/scholarship-app/views"

When attempting to render the request URL for an ID in my Express app, I encountered the following error: Error: Failed to find view "/id" in views directory "/home/USER/Desktop/scholarship-app/views" Here is a portion of my Express app code: app.get(&a ...

Change the structure of the content in a div

Seeking assistance with a slider code that switches between two dividers, previous and next. Each divider currently displays ten images in two parallel vertical lines. I am attempting to modify the layout so that each divider showcases five images on two p ...

A guide to transporting an item from coordinates {x,y} to {newx,newy} using Three.js

Given the coordinates X and Y of an object, where Z is always 0, I am seeking a way to smoothly move this object to a new location using Three.js, with a visible animation rather than suddenly appearing in a different spot. UPDATE: Below is a sample code ...

Customizing the appearance of Previous and Next elements using JavaScript

My challenge involves working with a form on a webpage where I do not have direct access to the HTML or CSS. Therefore, any modifications need to be made using JavaScript\JQuery. The form in question has a layout like this: https://i.sstatic.net/Czuo ...

Tips for transferring data from an HTML textbox to a JavaScript variable

I'm currently working on a form that fetches data from a database and dynamically stores it in a table. There's a button labeled "add" which, when pressed by the user, adds a new row to the table. I also have a hidden counter that keeps track of ...

Using jQuery to send emails

I have encountered an issue with my JavaScript code where it validates and sends an email through the Sendgrid API. Glimpse at the code below: var contact = new Vue({ el: '#form_contact', data: { company_name: null, fulln ...

What steps can be taken to prevent a child component from re-rendering when the parent updates the context or state in React JS?

How can I prevent a child component from re-rendering when the parent updates the context or state in React JS? I have already implemented React.memo, but the component still re-renders. Below is my child component: const Ab = () => { console.log(&q ...

Avoid binding an object in Vue.js when you intend to copy it to a different data attribute

I am facing a situation where I have an object retrieved from my API and need to replicate it to another object while loading a modal. The following method achieves the duplication: this.servicesForm.services = this.team.services; // New object ...

When implementing jQuery AJAX, remember to properly encode script tags to prevent any

Looking for a way to avoid script tags in content loaded through AJAX? Check out this approach: $.ajax({ cache: false, type: 'GET', url: 'index.html', success: function(response) { $(response).find('<sc ...

UI Select not found result event

Currently implementing https://github.com/angular-ui/ui-select and looking for a solution to trigger an event (such as opening a modal) when no results are found while using a filter. <ui-select ng-model="SelectedCustomer.selected" theme="select2"> ...

Using Typescript to pass inferred type to React's useCallback

Illustration: function useFunction(fn) { return fn; } type Data = { '/person': { person: any }, '/place': { place: any }, }; function useData<Path extends keyof Data>( path: Path, options: { callback?: (data: Data[ ...

How can you create a MUI textfield that only allows numerical values to be entered in the password field?

Need help setting up input type password to only accept numeric values. Looking to toggle the eye icon to switch between hidden password type and visible numeric type. Currently, when hidden, it changes to text type, but I want to keep i ...

How can I customize button colors in react-bootstrap components?

Changing colors in react-bootstrap may be a challenge, but I'm looking to customize the color of my button beyond the primary options. Any suggestions on how I can achieve this using JS and SCSS? ...

Arrange 3D blocks on a grid using ThreeJS with customizable dimensions

I've been experimenting with the voxel painter example found in the ThreeJS git repository. One change I made was adjusting the grid size to 5x5, but now the roll-over mesh doesn't align perfectly with the grid squares and overlaps between four ...

determine the height of a div using jquery calculations

If a div is positioned relative and contains child divs that are positioned absolute, the parent div will have no set height. However, if the contents of the div change dynamically, there should be a way to calculate and adjust the height of the parent acc ...

Sending a message to an iframe from a different origin using JavaScript

Just starting out with JavaScript and I'm attempting to send a message to my iframe in order to scroll it. Here is the code I am using: scroll(i) { var src = $("#iframe").attr("src"); $("#iframe").contentWindow.postMe ...

retrieving data from Redis with the help of Node.js

I'm having trouble with the code snippet below. Despite setting values for the left_label and right_label variables in Redis, they always seem to return as "true". I suspect this is due to the client.get function returning true when successful. How ca ...

Error in Winston: Unable to determine the length of undefined property

I encountered an issue with my Winston Transport in the express backend of my MERN app. The error message reads: error: uncaughtException: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefi ...

How to open a new window in a separate desktop on macOS using Javascript

I am currently browsing my website on a Mac computer. I am interested in opening a new tab on the second desktop using Mission Control. Is this achievable? If so, could you please guide me on how to do it? After searching extensively online, I have been u ...

Establishing the Time-to-Live (TTL) with Redis-OM and Node Object Mapping

Recently, I stumbled upon the exciting new Redis-OM Node Object Mapping feature. Although I have limited experience with Redis, I am eager to dive into it now. Currently, I have a basic function in place for creating rooms but I want these rooms to automa ...