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

featherlight.js - Execute code when modal is triggered

Situation with HTML <div id="form-lightbox"> <div class="form"> <div id="ajaxreplace"> <script type="text/javascript"> jQuery(function() { jQuery.ajaxReplace({ //parame ...

Automatically adjust the top margin of the content section to accommodate a fixed header height

After extensive searching, I've come across various solutions but none of them seem to fit my needs. I am a beginner/amateur developer. The issue I am facing is with a fixed header that resizes when scrolling. I understand that by adding padding-top: ...

Display the Material UI Switch in an active state even when the "checked" value is set to false

While using Material UI Switches with Formik, I've encountered an issue. When I toggle the switch to 'enable,' it automatically sets the value in Formik to "true," and when I toggle it to 'disable,' it sets the value in Formik to " ...

Tips for incorporating MIDI player for notes sequence using MIDI.js

Incorporating MIDI.js into my current project to play a sequence of MIDI notes. See below for the code snippet: for (var repeat = 0; repeat < melodyrepititions; repeat++) { for (var i = 0; i < composition.length; i++) ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Exploring the depths of npm in the realm of frontend development

Currently, I am delving into the realm of Javascript/Node development through self-teaching. While I grasp the concept of npm handling package installations for my Node application on the server side, I am struggling to comprehend how npm assists me with ...

What is the best way to incorporate autoplay video within the viewport?

My objective is for the video to automatically start playing when it enters the viewport, even if the play button is not clicked. It should also pause automatically when it leaves the viewport, without the need to click the pause button. <script src=& ...

Creating uniform URLs using MVC .NET routing: a guide

While using ASP.Net MVC 5 in .NET Framework 4.8, I am constantly facing a 404 error due to inconsistent URL generation. For instance, when including the _PageNav.chstml partial at the top of each page and adding @Url.Action("Index", new { controller = "Hom ...

Encountering a 500 server error while attempting to retrieve content from Google Images through the Web Speech API

My current project involves utilizing the Web Speech API to dynamically gather free images from Google. Here's how it works: I extract the search keyword using the Web Speech API in JavaScript. The keyword is then sent to the server (PHP) via an a ...

The `tailwind.min.css` file takes precedence over `tailwind.css` in my Nuxt

Having trouble configuring Tailwind to use a custom font without it overriding the tailwind.css file and not displaying the changes? https://i.stack.imgur.com/ExDCL.png Check out my files below. // tailwind.config.js const defaultTheme = require('ta ...

Customizing Geonames JSON Ajax Request

Having found the code I needed from a sample website, I am now seeking help to customize it to only display results from the USA. This is the current code snippet: $(function() { function log( message ) { $( "<div>" ).text( message ).pr ...

What causes getServersideprops to return undefined?

The data I am trying to fetch is showing as undefined in the console. Here is the code snippet: export default function Home({ data }) { console.log(data); return ( <div> <h2>Welcome !!</h2> </div> ); } export a ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...

VueJS - Input Image Display Issue Causing Browser Slowdown

I'm experiencing some issues with my VueJS component that includes a file input and displays an image afterwards. Strangely, this is causing my web browsers (both Firefox and Chromium) to freeze up and use massive amounts of CPU. I tried switching to ...

Filtering rows in JQgrid is made easy after the addition of a new record

Here's the situation I'm facing: Every second, my script adds a new record using the "setInterval" function: $("#grid").jqGrid('addRowData', id, data, 'first').trigger("reloadGrid"); However, when users apply filters while t ...

Error caused by live data dynamic update on Highstock chart: Cannot access property 'info' of undefined

Utilizing Laravel, I was able to create Highcharts by consuming data from a Rest API link (Spring app) at . The data is currently displayed statically, but I want to dynamically visualize it on charts. I attempted to follow this example on Fiddle and inte ...

AngularJS and Select2's Multiple - Tags feature can display tags intermittently, showing some and hiding others as needed

Currently, I am implementing AngularJS along with select2 (not using ui-select). In my view, the following code is present: <select name="rubros" id="rubros" class="select2 form-control" ng-model="vm.comercio.tags" ng-options="rubro.nombre for rub ...

Navigating through a URL to grab a specific JSON object: a step-by-step guide

When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...