Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end.

function findDateDifferences(obj1, obj2) {
  return Object.entries(obj1).reduce((diff, [key, value]) => {
    // Check if the property exists in obj2.
    if (obj2.hasOwnProperty(key)) {
      const val = obj2[key];

      // Compare the values of the properties in both objects.
      if (val !== value) {
        return {
          ...diff,
          [key]: val,
        };
      }
    }

    // Return the previous diff object if no differences found.
    return diff;
  }, {});
}

const x = {
  dateOfBirth: "Wed Jan 06 2021 12:00:05 GMT-0700 (Mexican Pacific Standard Time)",
  name: "test"
};
const y = {
  dateOfBirth: "2021-01-06T12:00:05.357",
  name: "test"
};


console.log(findDateDifferences(x, y));

In this scenario, the dates are the same but in different formats. How can I modify the function to recognize them as identical?

Answer №1

Steps to Compare Date Properties:

  • First, we check if the property is a date by using the isNaN() function along with the valueOf() function of the Date object.
  • If we only need the date without the time, we can utilize the toDateString() extension method of the Date object.

function compareDateProperties(obj1, obj2) {
  return Object.entries(obj1).reduce((diff, [key, value]) => {
    // Check if the property exists in obj2.
    if (obj2.hasOwnProperty(key)) {
      const val = obj2[key];

      if (typeof val === "string") {
        const obj1Date = new Date(value);
        const obj2Date = new Date(val);

        // Validate if the values are valid dates. If not, proceed with regular comparison.
        if (!isNaN(obj1Date) && !isNaN(obj2Date)) {
          return obj1Date.toDateString() !== obj2Date.toDateString() ? { ...diff,
            [key]: val
          } : diff;
        }

      }

      // Check if the property's value differs between obj1 and obj2.
      if (val !== value) {
        return {
          ...diff,
          [key]: val,
        };
      }
    }

    // Return the previous diff object if the property doesn't exist in both objects.
    return diff;
  }, {});
}

const objA = {
  dateOfBirth: "Wed Jan 06 2021 12:00:05 GMT-0700 (Mexican Pacific Standard Time)",
  name: "test",
  num: 1
};
const objB = {
  dateOfBirth: "2021-01-06T12:00:05.357",
  name: "test",
  num: 2
};


console.log(compareDateProperties(objA, objB));

Answer №2

The best approach would be to compare

new Date(val) !== new Date(value)
, but due to the missing timezone in the second time format, it leaves room for interpretation. Additionally, you specified that only the date itself is important, not the specific time of day.

function findPropertyDiscrepancies(obj1, obj2) {
  return Object.entries(obj1).reduce((discrepancies, [key, value]) => {
    // Check if the property exists in obj2.
    
    if (obj2.hasOwnProperty(key)) {
      const val = obj2[key];

      // Determine if the values are different between obj1 and obj2.
      if (new Date(val.split(" ").slice(2,5).join(" ")) !== new Date(value.split("T")[0])) {
        return {
          ...discrepancies,
          [key]: val,
        };
      }
    }

    // Return the existing discrepancies object if no differences were found.
    return discrepancies;
  }, {});
}

const data1 = {
  dateOfBirth: "Wed Jan 06 2021 12:00:05 GMT-0700 (Mexican Pacific Standard Time)",
  name: "test"
};
const data2 = {
  dateOfBirth: "2021-01-06T12:00:05.357",
  name: "test"
};

console.log(findPropertyDiscrepancies(data1, data2));

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

Working with relative paths in React Native TypeScript using WebStorm

My variable color is located in the path app/theme. To set it up, I created a package.json file in app/package.json with the following content: { "name": "app" } Now, to import color in TypeScript files, I use the following syntax: import { color } fro ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

A code to ensure input values are always set to the maximum possible value

I recently developed a script that monitors the live value property of 3 <input> elements, correcting them if the live value is outside the specified range. However, I encountered an issue where the script automatically sets the value to the max as s ...

Contrasts between the storage of data in a static function versus a static object

Trying to figure out the best way to reset a react class component back to its initial state, I came across two different implementations. In my own version, I created an object with initial values and set the component's state equal to it: // My imp ...

Problems with radio button serialization in jQuery form plugin

I've created a basic form: <form class="dataform" method="post" id="settings" action="/"> <input type="radio" name="shareSetting" value="n"/> <input type="radio" name="shareSetting" value="y"/> <input type="button" na ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

Is there a way to change an ISO 8601 date into the format '/Date(1525687010053)/' using JavaScript?

Is there a way to convert a date value that is formatted as 9999-12-31T00:00:00Z to the format /Date(1525687010053)/ using javascript? I tried implementing the following code, but it doesn't seem to be working: var datevalue = '9999-12-31T00:00 ...

Helping JavaScript determine my current location on the website

One issue I am facing is with a single template file that renders pages that may look similar but have slightly different behaviors. The header and text boxes are filled by the template language, while the canvas content distinguishes the pages. Different ...

Steps for resolving the error message: "An appropriate loader is required to handle this file type, but there are no loaders currently configured to process it."

I am encountering an issue when working with next.js and trying to export a type in a file called index.ts within a third-party package. Module parse failed: Unexpected token (23:7) You may need an appropriate loader to handle this file type, current ...

Struggling to get my JavaScript function for calculating one rep max to work, need some help figuring out the issue

I have been working on a one rep max calculator using the Epley Formula. However, when I try to call the function, it returns as undefined. I have utilized the parameters weight and reps, both of which are parsed as integers, believing that they would be e ...

Create dynamic transitions for hidden elements using a special technique

Is it possible to smoothly transition a div element from display:none to display:block? I attempted to first set the display to block and then apply a transition, but it doesn't seem to be working as expected. HTML <input type="text" class="inp"& ...

The scrolling speed of the mousewheel in Firefox is notably slower compared to that of Google Chrome

Kindly review this sample link: When I test the above example in Chrome and scroll using the mouse wheel, the page moves up by 100px each time. The Y position is displayed as well. However, if I try the same page in Firefox 26.0 and scroll with the mouse ...

Fixing 500 (Internal Server Error) in Vue.js and Laravel: The Ultimate Guide

Working on a university project using Vue.js and Laravel, I need assistance with sending information to the API. I'm trying to use axios for the POST request, but it's giving me an error: 500 (Internal Server Error). I can't seem to identif ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

Peculiar redirection encountered while handling a form with checkbox option

When I try to submit the form in Chrome, the PHP file does not get called and I am redirected to another HTML page. However, in Firefox, when I select three checkboxes, it redirects me to that same HTML page as in Chrome. I even tried using radio buttons i ...

I possess a list of unique identifiers and require the ability to either update an existing object within an array contained in a MongoDB document, if it exists,

I am facing a challenge in updating a specific element within an array in a MongoDB document. I have multiple IDs of that array and need to update the matching element using those IDs. data= [ { "planId" : "plan_FVNvrmjWT7fRDY", "startTime": ...

Even when the outcome is not what was anticipated, mocha chai still manages to ace the examination

When testing my REST API response with mocha, chai, and express, I set the expected status to 201 but unexpectedly got a passing test result it('janus post', () => { request('https://***') .post('/***') .attach(&a ...

The issue with AngularJS multiple $http requests failing to fetch accurate data

I'm having issues with my AngularJS controller and service modules. I want to refresh custController.allCustomers after adding a new customer so that the UI displays the new data. However, when I call custController.createCustomer, the new customer do ...

A guide to sharing session variables with express views

Struggling to access session variables in EJS views and encountering various challenges. To locally access req.session, I've implemented middleware as outlined in this guide on accessing Express.js req or session from Jade template. var express = re ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...