Calculate the date difference in Nuxt by leveraging the @nuxtjs/moment module

I'm a Nuxt newbie facing an issue with calculating the difference between two dates (user input date and current date). The code I am using works fine in most cases, but when the input date is '2020-03-31' or '2020-01-30', the console displays NaN years NaN month NaN day.

How can I resolve this? What mistake am I making?

I suspect that the months in the moment module start from 0-11 while my input months range from 1-12. Could someone please provide a sample code for obtaining the difference between 2 dates and outputting the year, month, and day?

Using module: https://www.npmjs.com/package/@nuxtjs/moment

methods: {
    //example input format >>> date = '2020-08-21'
    calcDate(date){
      let nowDate = moment(new Date().toISOString().substr(0, 10).split('-'));
      let pickDate = moment(date.toString().substr(0, 10).split('-'));
      let dateDiff = moment.duration(nowDate.diff(pickDate));
      console.log(dateDiff.years() + ' years ' + dateDiff.months() + ' month ' + dateDiff.days() + ' day ')
    }

},

Thank you!

Answer №1

To correctly parse the date, you should specify the date format

methods: {
    //example input format >>> date = '2020-08-21'
    calculateDate(date){
      let currentDate = moment();
      let selectedDate = moment(date.toString(), 'YYYY-MM-DD');
      let difference = moment.duration(currentDate.diff(selectedDate));
      console.log(difference.years() + ' years ' + difference.months() + ' month ' + difference.days() + ' day ')
    }

},

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

Show Cooking Ideas on the Website

This particular project is focused on showcasing various recipes and facilitating multiple actions such as addition, deletion, and modification of these recipes. However, I encountered an issue where the recipes were not being displayed in the browser desp ...

Utilizing chrome.scripting to inject scripts in TypeScript

I am currently facing an issue wherein I am attempting to integrate chrome extension JavaScript code with TypeScript: const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); let result; try { [{ result }] = await c ...

Transform the string with binary hexadecimal characters in ASCII into a Buffer

Currently, I am utilizing node.js for my project. Within my code, there is a string variable called msg_str that contains the value "0102ab00aabb00". My goal is to convert this ASCII binary hex representation into a Buffer and have it displayed as <01 ...

Having trouble with adding an event listener on scroll in React JS. Need assistance in resolving this issue

I'm having trouble adding an event listener for when a user scrolls in my web app. componentDidMount = () => { let scrollPosition = window.scrollY; let header = document.getElementById("topBar"); window.addEventListener(&ap ...

combine and refresh identical items within an array

Currently, I am in the process of creating a prototype for an item-list and a shopping-cart. Both components function as standalone entities but are connected through a vuex-store. The item-list contains various elements that can be added to the shopping-c ...

Trouble with implementing an onclick event listener in a foreach loop

While generating and adding HTML in a for loop, I noticed that adding onclick events within the same loop is not functioning correctly: items.forEach(item => { itemHtml = `<div class="${item.id}">${item.id}</div>`; $(".it ...

Steps for creating a JSON object to send batch emails using Mailgun

I am looking to dynamically create a JSON object named recipient-variables using two separate arrays - one for emails and the other for first names and IDs. How can I write JavaScript code to achieve this? 'recipient-variables': '{"[em ...

I have a Key in my component, but it is still searching for a unique key

Just diving into React JS and attempting to transfer data from one component to another using the Link to method I found online... Error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Checking the render method of Videos. Refe ...

Tips for conducting an HTTP request test within my application

I am currently facing a challenge while attempting to develop unit tests for my application. Within my controller, I have the following code snippet: $scope.test1 = function() { productFactory.getName() .then(function(products){ ...

Is there a way to exchange the chosen options between two bootstrap-vue multiple select boxes?

Is there a way to switch the selected options between two bootstrap-vue multiple select boxes? I am trying to create a UI similar to the image shown below but I am struggling with writing the method. This is how I have written the template: https://i.sst ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

The Datatable plugin is unable to effectively customize tables that are loaded dynamically

Within my single page application, the home page initially loads all static resources and js files. Subsequently, upon a user click event, the table is dynamically loaded. Unfortunately, the datatable customization does not seem to be applied on the newly ...

Challenge with SSL when Vue JS and Laravel are running on the same server but on separate ports

I'm encountering an issue with installing SSL on my production server. My setup includes running Laravel on port 80 and Vue.js on port 8080, with an SSL certificate already installed. However, when attempting to make a request to port 8000, I'm ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Update content without reloading the page

I've implemented a function to delete an image in my action.js file: export const removeImage = (id, image_id) => async () => { try { const response = await axios.delete( `localhost:3000//api/v1/posts/${id}/delete/${image_id}`, ...

vuex: The decision between using $store.commit and directly calling the function

Recently, I discovered an interesting technique where store mutation functions can be passed into HTML events. Here's an example: //In the template <input name="the_field" :value="the_field" @input="updateField"/> // In the component methods ...

Issue with displaying a vTable component in VueJS / Vuetify

I am struggling with this basic HTML/Vue/Vuetify code snippet below, and I can't seem to get it functioning as intended. const { createApp, computed, ref, reactive } = Vue; const { createVuetify } = Vuetify; const ...

Upon initiating a refresh, the current user object from firebase Auth is found to be

Below is the code snippet from my profile page that works perfectly fine when I redirect from the login method of AuthService: const user = firebase.auth().currentUser; if (user != null) { this.name = user.displayName; this.uid = user.uid; } e ...

Converting Javascript tools into Typescript

I'm currently in the process of migrating my Ionic1 project to Ionic2, and it's been quite an interesting journey so far! One challenge that I'm facing is how to transfer a lengthy list of utility functions written in JavaScript, like CmToFe ...