What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected.

The date is retrieved in the following code:

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = (today.getFullYear());
today = dd + '/' + mm + '/' + yyyy;

The actual comparison is being performed here:

for (const event of events) {
        if (event.fecha_fin >= today  && event.hora_fin > my_time) {
          console.log(event.fecha_fin > today)
          eventsWithLowestPrice.push(event.id_evento_fk)
          console.log(event.id_evento_fk)
        }
      }

The data type of event.fecha_fin is currently set to "Any".

I have attempted changing both fecha_fin and today into "Number" data types without success. I am unsure of how to proceed.

In trying to adjust the data types of "today" and "fecha_fin" to "Number", I have encountered challenges and require further guidance.

Answer №1

Transform the strings into dates using

function convertStringToDate(str) {
  const [dd, mm, yyyy] = str.split('/');
  return new Date(yyyy, mm - 1, dd);
}

and then compare the dates:

for (const event of events) {
  const date1 = convertStringToDate(event.end_date);
  const date2 = convertStringToDate(today);
  if (date1 >= date2 && event.final_hour > my_time) {
    console.log(date1 > date2)
    eventsWithLowestPrice.push(event.event_id)
    console.log(event.event_id)
  }
}

For instance:

function convertStringToDate(str) {
  const [dd, mm, yyyy] = str.split('/');
  return new Date(yyyy, mm - 1, dd);
}

const events = [{end_date: '01/01/2020', final_hour: 2}];
const today = '02/02/2002';
const my_time = 1;

for (const event of events) {
  const date1 = convertStringToDate(event.end_date);
  const date2 = convertStringToDate(today);
  if (date1 >= date2 && event.final_hour > my_time) {
    console.log(date1 > date2)
    //eventsWithLowestPrice.push(event.event_id)
    console.log(event.event_id)
  }
}

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

Having some issues with validating numbers in typescript

When implementing react hook form in my React app, I encountered an issue while validating specific fields and had to add some conditions to the schema. yup .object({ test1: yup.number().when('test2', (test2: number, schema: yup.NumberSchem ...

Navigating to a specific attribute within a higher-level Component

Within my top-level Component, I have a property that is populated with data from an HTTP source. Here is how it is implemented in a file named app.ts: import {UserData} from './services/user-data/UserData'; Component({ selector: 'app& ...

Avoiding unnecessary re-renders of a parent component caused by a child component

I'm facing rendering problems and would greatly appreciate any assistance. I attempted to use useMemo and useCallback, but it resulted in the checkbox breaking. Within a component, I am displaying information from an object. Let's consider the fo ...

Accessing loop variables in Render and passing them into componentDidMount() in ReactJS to include as a query parameter in an API call

Within the render function, I am using a loop to rotate an array of coordinates in order to position markers on a map. {coords.map(({ lat, lng }, index) => (code goes here and so on))} I intend to replace query parameters with the variable generated f ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

Determine the total amount of pages generated from the Twitter search API

Can the Twitter search API provide a count of the pages returned? I'm curious if there is a method to determine how many pages are available for a particular query. ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

Ways to verify whether a string has already been hashed in Node.js utilizing crypto

I am currently working on an application that allows users to change their passwords. For this project, I am utilizing Node.js along with the mongoose and crypto libraries. To generate hashes for the passwords, I have implemented a hook into the model&ap ...

Infinite scroll layout meets Semantic UI visibility for a dynamic user experience

I am attempting to implement an infinite scrolling Masonry layout within the Semantic UI framework, utilizing the pre-existing visibility function. While everything appears to be functioning correctly, I am encountering difficulties with getting Masonry t ...

Is there a way to adjust the text color of a label for a disabled input HTML element?

If the custom-switch is active: the label text color will be green. If the custom-switch is inactive: the label text color will be red. A JavaScript (JQuery) method call can be used to activate one button while deactivating another. The Issue It appe ...

What steps can I take to stop Vetur and TypeScript from displaying duplicate TypeScript warnings in VSCode?

I have a Vue2 project using TypeScript in VSCode with Vetur and TypeScript extensions installed. Whenever there is a TypeScript warning, both the TypeScript and Vetur overlays show duplicate warnings. Example of duplicate warnings Also, the intellisense ...

There's just something really irritating me about that Facebook Timer feature

Have you ever noticed the timers constantly updating on Facebook? Whether it's an Ajax Request triggered by a timer or a client-side timer, there are numerous timers being used. Does this affect the performance of the website, and is there something c ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Implementing the adding functionality within an ejs file

I'm currently working on a project that involves fetching data from an API using a simple JavaScript file upon clicking a button. Initially, everything was functioning properly when both the HTML file and JS file were in the same folder, and I could a ...

Encountering an issue with the `className` prop not matching when deploying to Heroku, yet the functionality works perfectly when testing locally

I encountered this specific error message: The className property did not match. On the server: "jss1 jss5" Client side: "makeStyles-root-1 makeStyles-root-5" This issue only arises when deploying to Heroku. Locally, everything runs ...

What is the most efficient way to apply multiple combinations for filtering the information within a table?

I'm facing an issue with my Angular project. I have 4 select boxes that allow users to apply different filters: office worker project name employee activities The problem I'm encountering is the difficulty in predicting all possible combination ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Winning awards through the evaluation of possibilities

I became intrigued by the idea of using a chance algorithm to simulate spinning a wheel, so I decided to create some code. I set up an object that listed each prize along with its probability: const chances = { "Apple" : 22.45, & ...

I'm looking for the configuration of function definitions for the Jasmine npm module within an Angular project. Can

When a new Angular project is created, the *.spec.ts files provide access to Jasmine functions such as "describe", "beforeEach", and expect. Despite not having an import clause for them in spec.ts files, I can click on these functions and navigate to their ...