Output the word 'Days', 'Months', or 'Years' depending on the value of N, which represents the number of days

I am currently utilizing moment.js in conjunction with vue 3. I've implemented a function that calculates the disparity between two dates. The functionality works as expected, but here's where my query comes in. The function is structured like so:

methods: {
    getDateDifference (date) {
        var date = moment(date, 'YYYY MM DD')
        var today = moment()
        return today.diff(date, 'days')
    } 
}

At this point, I can effectively determine the difference between the passed date and the current today. However, the issue arises when I aim to ascertain whether the returned number of days falls in a specific range - greater than a week but less than a month. In such cases, I would prefer to display the value in terms of weeks, rather than just stating 28 days, for instance. Additionally, if the number of days exceeds 28, it should be shown in months, and likewise, for over a year, they should be presented as years.

In essence, instead of showing

26 days

I'd like the system to evaluate if this can be converted to weeks, resulting in:

3 weeks

Furthermore, if feasible, the option to display the duration in terms of months or years as well should be provided.

Answer №1

moment.js offers a solution using the duration API:

To obtain the milliseconds:

methods: {
    getDateDifference (date) {
        var date = moment(date, 'YYYY MM DD')
        var today = moment()
        return today.diff(date)
    } 
}

Next, utilize:

/* Unsure about the object that contains methods */ 
let shortest = moment.duration(obj.methods.getDateDifference(date)).humanize();

This will display months instead of days if the duration exceeds a month, years instead of months, and so on.

Check out Moment.js duration.humanize documentation for more details

Answer №2

An effective way to handle time intervals is by utilizing an array that links specific durations in days with the level of detail in your output.

const timeframes = [
    {duration: 366, type: "years"},
    {duration: 31, type: "months"},
    {duration: 7, type: "weeks"},
    {duration: 0, type: "days"}
];

daysElapsed = today.diff(date, "days");
for (let j = 0; j < timeframes.length; j++) {
    if (daysElapsed >= timeframes[j].duration) {
        return today.diff(date, timeframes[j].type);
    }
}

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

Is there a way to modify the props.data in a child component?

I need assistance with displaying a range from an array that is passed into a child component. Currently, my Parent component looks like this: import data from './data.json' return ( <Cell symbol={data.symbol} number={data.number} /> ) ...

What is the process for removing an item from a JSON file using an HTTP DELETE request in a Node.js environment?

Essentially, I have a JSON file containing user and group data and I need to delete a specific group from it. Below is a snippet of the JSON file named authdata.json: [{ "name": "Allan", "role": ["Group Admin", "Super Admin"], "group": ["Cool- ...

Adjust the width to ensure the height is within the bounds of the window screen?

I am currently in the process of developing a responsive website, and my goal is to have the homepage display without any need for scrolling. The layout consists of a 239px tall header, a footer that is 94px tall, and an Owl Carousel that slides through im ...

Expressing the power of multiple nested routers

Can multiple nested routers be implemented in an Express server? Imagine running a vehicle servicing business and wanting to organize the API into different services, each with its own set of actions: app.use('/clean', cleanRoutes); app.use(&apo ...

Calculate the sum of a specific column in an HTML table using JavaScript after

I have a function called CalColumnHistDEPOSITO() that I use to sum a table column as it loads from the server side into my HTML page. However, when I apply a filter, it continues to sum the entire table ignoring the filter. (function() { 'use stric ...

Vue.js is experiencing functionality issues on mobile devices and other connected devices, however, it is operating smoothly on desktop devices when localhost is running

I recently ran into an issue while trying to run my Laravel project on localhost and connect it to other devices like mobiles and desktops/laptops using the local address. The function works perfectly on the hosting desktop but fails to work on other devic ...

Abort S3 file upload using ASW-SDK

Is there a way to abort an upload without raising an error Upload aborted. when calling upload.abort()? import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage"; cons ...

What is the best way to ensure a cron job executing a Node.js script can access variables stored in an .env file?

Currently, I have a scheduled job using cron that runs a Node.js script. This script utilizes the dotenv package to access API keys stored in a .env file. Running the Node.js script from the command line retrieves the variables from the .env file successf ...

Exploring the angular js repeater component's context menu options

In one of my current projects, the client has specifically requested a right-click menu feature. However, the challenge lies in ensuring that the function triggered by the menu options has access to relevant information from the model. For instance, you ...

Ways to inform a subelement that a task is complete?

I have a child component that displays a list of orders passed from the parent. I want to include a "Reload" button inside the child component that, when clicked, triggers a function in the parent component to reload the orders. Upon clicking the reload b ...

Issues with sending empty strings to an API in Vue Js

My code below is designed to update data using a Node Js REST API. The remaining field contains an equation using v-model=remaininginst to calculate and store the result in remaininginst. However, when I check the console.log, I am getting NaN empty data s ...

What is the best way to enhance a tool-tip with images or legends?

Currently, I have implemented a tool-tip feature which works for a text box. However, the issue is that users are unaware of the presence of the tool-tip for the text box until they hover over it. My question is, how can I make it more obvious to users t ...

Is there a way to exclude a specific div based on two select choices?

Check out my Fiddle demonstration here $('select#classes').on('change', function() { var selectedClass = $(this).val(); $('.col-sm-6:not(:contains(' + selectedClass + '))').hide(); $('select#subjec ...

What steps can be taken to verify that the submitted data is a legitimate numerical pair?

When I receive a string, it should be in the following format: number,number For example: 34.798,52.123 I need to verify that the number is indeed in this format before assigning it to variables and performing calculations. There is also a concern that ...

Pop-up alert for text sections that are longer than a specific character limit

As I work on a website featuring dynamically generated blog posts of varying lengths, I'm looking to restrict the height of each post to 250px. Should a post exceed this limit, I want to truncate it and include a "read more" link that opens a modal ov ...

Adding elements to a JSON array in JavaScript/AngularJS

Looking for help with inserting a new item "uid" into a JSON array. Here is the initial array: var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}] The desired output after inserting the "uid" would be: var testArr=[{name:"nam ...

End the response after sending with res.send() within the module

I am in the process of developing a module for validating requests that come through req.body. Instead of repeating the same code snippet in every server request, I aim to consolidate it into a single line within a module. const errors = validationResult( ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

Having trouble getting Tesseract.js to work with an Electron App built using Vue and vue-cli-plugin-electron-builder

Struggling with using Tesseract OCR in a project created with vue-service-cli? You're not alone. I've been facing issues trying to load lang.traineddata both locally and remotely. Despite attempting various solutions found in tesseract.js repo an ...

How can we avoid having the same event duplicated on a canvas, leading to the unnecessary rendering of multiple layers of the same event?

I have encountered an issue with my Chrome extension on certain websites where, upon scrolling, the same element is rendered multiple times, causing a significant decrease in performance. This rendering occurs as soon as I stop scrolling, leading to layers ...