Issue with moment library causing date to appear incorrect on 31st day

I am experiencing an issue when finding the difference between 2 dates in years. Specifically, when I choose the 31st date, it returns an invalid result as NaN.

However, with other dates, the calculation displays the correct outcome.

const selectedValue = moment('31-8-2022');
const today = moment();
const yearDiff = today.diff(selectedValue, "year");
console.log(yearDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Answer №1

Upon testing the provided sample code, a deprecation warning is triggered:

Warning: The value provided does not adhere to a recognized RFC2822 or ISO format. moment construction defaults to js Date(), which may not be consistent across all browser types and versions. It is advised to avoid non RFC2822/ISO date formats as they will be phased out in a future major update. Additional information can be found at http://momentjs.com/guides/#/warnings/js-date/.

By entering the date in ISO format, the code functions correctly:

const selectValue = moment('2022-08-31'); // 2022-08-31 instead of 31-8-2022
const today = moment();
const yearDiff = today.diff(selectValue, "year");
console.log(yearDiff);

Answer №2

When utilizing 'DD-MM-YYYY' with momentjs, it results in an invalid date format.

const selectedValue = moment('30-08-2022').format('DD-MM-YYYY');
console.log(selectedValue)
 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

To ensure it is a valid date, include 'DD-MM-YYYY' in the second parameter of the moment function after the date and format it.

const selectedValue = moment('30-08-2022','DD-MM-YYYY').format('DD-MM-YYYY');
console.log(selectedValue)
     



  
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

If you must use 'DD-MM-YYYY' in your code without encountering a deprecation warning, you can do the following

const selectedValue = moment('30-08-2022', 'DD-MM-YYYY').format('DD-MM-YYYY');
console.log(selectedValue)
const today = moment().format('DD-MM-YYYY');
console.log(today)
const yearDiff = moment(today, 'DD-MM-YYYY').diff(moment(selectedValue, 'DD-MM-YYYY'), 'years');
console.log(yearDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.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

increasing the size of the input thumb compared to the others

Hello fellow React developers, I'm currently learning by coding and I have a question about a slider. I'm trying to make the thumb of the slider bigger, but when I increase its size it doesn't fully display within the input area (as you can ...

JavaScript causing Axios network error

Recently, I've started exploring the combination of axios and stripe in my project but unfortunately, I have encountered some challenges. Whenever I attempt to initiate a post request using axios, an error pops up which looks like this: https://i.sta ...

What is the best way to remove a specific item from a list of maps in DynamoDB based on a particular attribute value within the

Below is an example of a list I have: { "favorites": [ { "createdAt": 1448998673852, "entityId": "558da3de395b1aee2d6b7d2b", "type": "media" }, { "createdAt": 1448998789252, "entityId": "558da3de395b1aee2d6b7d83 ...

Add AngularJS to an AJAX call when the user clicks on it

I'm currently exploring the SoundCloud API and looking to implement a feature where users can add a song to the page by clicking on it from the search results. I've decided to utilize Plangular, which you can find more information about here. How ...

Tips for comparing two arrays in node.js

I am faced with the task of comparing two arrays. let runArray = ['Welcome', 'Hello'] let data = [{ Node:'Good', Session:'2', Run:'Welcome', Run_Group:'Display', Elapsed_Ms: '1000& ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

Using Mongoose to Add Documents

Showing off my Mongoose schema: let DiscountSchema = new Schema({ deal:{ discountid:{ type: String, require: true, unique: true, }, title: String, }, // Embedded sub-section deta ...

Is there a way to achieve element scrolling similar to scrollLeft within a scrollable container without using JavaScript

Looking for a CSS Solution: Is there a way to achieve element.scrollLeft functionality in CSS without using javascript? I want to pre-scroll a scrollable container. Situation Overview: I have a scrollable container that houses various items. Some instanc ...

Encountering an error in Angular when trying to add a dynamic component

I have a straightforward test code for implementing dynamic components in Angular 4. @Component({ selector: 'component', template: ` <ul><li #item *ngFor="let number of list">{{number}}</li></ul> <ng-temp ...

JavaScript Error: Unable to execute getJsonData due to function not found

I am encountering an issue with a function that retrieves JSON data from a URL Here is the code snippet: var retrieveJsonData = function(uri,callback){ $.ajax({ type: "GET", dataType: "jsonp", url: uri, jsonpCallback: 'r ...

What is the most effective way to display a card with varying values depending on the user's input in a form?

For a while now, I've been grappling with a particular challenge. In my project, I am utilizing multiple states to display values within a card after they are entered into a form. The first state captures the values and modifies the initial state, whi ...

Using the Javascript function getElementById to retrieve user input for passing a RSS FeedURL

I've been working on creating a basic form where users can input a Feed URL and see the contents displayed on the HTML page. For testing purposes, I have used "https://jquery-plugins.net/rss" as the feedUrl, and it has been functioning normally. This ...

The MaskedInput text does not appear properly when it is passed through the props

Currently, I am facing an issue with a Material UI OutlinedInput along with the MaskedInput component from react-text-mask. Everything works fine when I input text initially and the element is not in focus. However, upon closing and reopening the Dialog wi ...

Utilizing Vue's v-for directive to manipulate data through custom looping

When I loop through my data using v-for, I find myself unsure of how to display the data with a custom looping method, such as using modulus. I aim to display the data in groups of three items, assigning a different class to every 3 items. The desired st ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

The concept of an HTML pop-up message that hovers above the content

While working on my HTML form, I encountered an issue regarding the display of a warning message notifying users about the caps lock being on. Currently, the warning is shown correctly in a div located to the right of the text box. However, this div's ...

What causes useEffect to run twice in React and what is the best way to manage it effectively?

I'm currently facing an issue with my React 18 project where the useEffect hook is being called twice on mount. I have a counter set up along with a console.log() inside the useEffect to track changes in state. Here's a link to my project on Code ...

Scroll to the top of jQuery DataTables when clicking pages in a random order from the bottom to the top and

In my current project, I am working with jQuery Datatables and I need to customize its default behavior. Currently, when I navigate to page 61, the page scroll remains at the bottom of the page. However, if I then click on a lower page number like 60, th ...

Retrieve the output of a function once the function has completed

I'm facing an issue where I need to wait for a function to return a value from my MySQL table before using it as a return for my const ProjektNameIntentHandler. Here is the relevant code snippet: const ProjektNameIntentHandler = { canHandle(handlerIn ...

Creating a Three-Dimensional Bounding Box in THREE.js

After successfully utilizing the OBB.js in three.js examples to fetch the center, halfSize, and rotation values, the next step is to determine how to calculate the 8 corners of the bounding box based on this information. Additionally, we need to understa ...