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

What is the best method for storing dynamic values and attribute labels in a state within a React.js application?

I am currently working with react js. On my single product page, I have an array of objects called attributes that I need to display in the user interface. Here is a preview of how it looks: https://i.sstatic.net/GttrD.png My goal is to retrieve and stor ...

Deleting images from Firestore using a Vue.js componentReady to learn how to remove images

I recently came across a Vue.js image uploader component that I am trying to repurpose (https://codesandbox.io/s/219m6n7z3j). This component allows users to upload images to Firebase storage and save the downloadURL to firestore for continuous rendering of ...

What is the process for enabling HLS.js to retrieve data from the server side?

I have successfully implemented a video player using hls.js, and I have some ts files stored in https:/// along with an m3u8 file. To read the content of the m3u8 file, I used PHP to fetch it and sent the data to JavaScript (res["manifest"] = the content ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

Differences between the application/xml and text/xml MIME types

How can I receive an XML response from a servlet? The servlet returns a content type of "application/xml". When using XmlHttpRequest, I am able to get responseText, but not responseXml. Could this be related to the content type or the request type (I' ...

The storage capacity of localStorage is insufficient for retaining data

While I was trying to troubleshoot an error, I encountered another issue. var save_button = document.getElementById('overlayBtn'); if(save_button){ save_button.addEventListener('click', updateOutput);} This led to the following ...

Combining routes in Express and Angular can be achieved by leveraging the power

How can I successfully integrate Jade AngularJS with ExpressJS? I have an app.js file for Express to run the server using Grunt. This app.js file renders home.jade which leads me to the home page. On the homepage, I have implemented AngularJS. I also creat ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

React-native horizontal sliding plugin

Can anyone recommend a reliable horizontal slider plugin for react-native? I've come across some options, but they haven't been working as smoothly as I'd hoped. ...

Tests using Cypress for end-to-end testing are failing to execute in continuous integration mode on gitlab.com

Challenges with Setting Up Cypress in Gitlab CI We have been facing difficulties setting up Cypress in the CI runners of gitlab.com using the default blueprint from vue-cli to scaffold the project. Despite trying various configurations in the gitlab.yml f ...

Is there a way to extract information from my JSON file and display it on my website?

My aim is to populate my HTML page with data from a JSON file. Approach I created a JavaScript file: update-info.js In this file, I used an AJAX call to retrieve data from my JSON file data.json If the request is successful, I utilized jQuery's .htm ...

Find the variance between the sums of columns 3 and 5 using Angular

Is there a method to calculate the variance between column 3 and the last one in a table? <body ng-app="Test"> <section style="margin-top:80px"> <h3>Plastic Calculator Form Version 2.0</h3> <div ng-controller="TestCo ...

Generate a responsive list with a pop-up feature under each item (using Vue.js)

Currently, I believe that Vue may not be necessary since most tasks can be done using JavaScript and CSS. I am attempting to design a list layout as follows: [A] [B] [C] [D] When an item is clicked, the information about that specific item should ...

How can I optimize the performance of JS-heavy pages on mobile devices?

As a website owner, I strive to optimize the performance of my site on mobile devices without the need for a separate "mobile-friendly" version or replacing large sections of code. With around 100K of JS code, including jQuery, I am determined to enhance b ...

A highly effective method for nesting items within a list through recursive functions

I am currently in the process of developing my own commenting system because I have found that existing platforms like Disqus do not meet my specific needs. My backend is built using NodeJS and MongoDB, and I need to execute two primary queries on my data ...

Strategies for managing the #document element within an iframe

While testing the current portal, I encountered an issue where I couldn't create any xpath locators. After some investigation, I realized that the problem stemmed from an '#document' causing the path to be cut off and redirecting the "copy x ...

Vue.js custom confirmation component failing to open within v-menu

I am having trouble displaying a confirmation component every time a button in the header is clicked. Currently, it only opens when clicking elements outside of the dropdown using v-menu. App.vue <template> {{isConfirmDialogVisible}} <div cla ...

Master the art of displaying complete text when zooming in and elegantly truncating it when zooming out

I am currently working on a data visualization project using d3.js. The tree chart that I have created is functioning well, but I would like the text to react dynamically when zooming in and out. You can find the code for my project on this JSFiddle page. ...