Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks?

I am currently running this code:

getDateStrings() {
  console.log(req_creation_date);
  const today = new Date();

  const creation_date = new Date('2020-01-06T20:24:00.000Z');

  const creation_date_diff = Math.abs(today.getTime() - creation_date.getTime());
  const creation_date_diffDays = Math.ceil((creation_date_diff / 1000));
  console.log(creation_date_diffDays);
  const creation_date_diffDays_days = Math.ceil((creation_date_diff / (1000 * 3600 * 24)) - 1);
  console.log(creation_date_diffDays_days);
  const y = Math.floor(creation_date_diffDays / 31536000);
  const ms = Math.floor(creation_date_diffDays % (3600 * 24 * 7 * 4.34524 * 12) / 2592000);
  const w = Math.floor(creation_date_diffDays % (3600 * 24 * 7 * 4.34524) / 604800);
  const d = Math.floor(creation_date_diffDays % (3600 * 24 * 7) / 86400);
  const h = Math.floor(creation_date_diffDays % (3600 * 24) / 3600);
  const m = Math.floor(creation_date_diffDays % 3600 / 60);
  const s = Math.floor(creation_date_diffDays % 60);

  const yDisplay = y > 0 ? y + (y === 1 ? ' year, ' : ' years, ') : '';
  const msDisplay = ms > 0 ? ms + (ms === 1 ? ' month, ' : ' months, ') : '';
  const wDisplay = w > 0 ? w + (w === 1 ? ' week, ' : ' weeks, ') : '';
  const dDisplay = d > 0 ? d + (d === 1 ? ' day, ' : ' days, ') : '';
  const hDisplay = h > 0 ? h + (h === 1 ? ' hour, ' : ' hours, ') : '';
  const mDisplay = m > 0 ? m + (m === 1 ? ' minute, ' : ' minutes, ') : '';
  const sDisplay = s > 0 ? s + (s === 1 ? ' second ' : ' seconds') : '' ;
  console.log(yDisplay, msDisplay, wDisplay, dDisplay + hDisplay + mDisplay + sDisplay);
}

Since 06-06-2020, exactly 60 days have passed up to now.

The output shows "2 months, 4 weeks, 4 days, 21 minutes, 10 seconds" which seems incorrect. It should be more like "2 months, 21 minutes, 10 seconds."

I'm struggling with another date, January 15, 2020, where 51 days have elapsed. However, the result is "1 month, 2 weeks, 2 days, 41 minutes, 43 seconds," totaling 46 days instead of the correct "1 month, 3 weeks, 0 days, 41 minutes, 43 seconds."

Thank you so much for any assistance!

Answer №1

I utilized moment.js to create a customized sandbox. The intention was to mirror your code as closely as possible. Below is the code snippet:

import "./styles.css";
import moment from "moment";

const getDuration = (startDate, endDate) =>
  moment.duration(moment(endDate).diff(moment(startDate)));

function getDurationText(startDate, endDate) {
  const duration = getDuration(startDate, endDate);
  const years = duration.years();
  const months = duration.months();
  const weeks = duration.weeks();
  const days = duration.subtract(weeks, "w").days();
  const hours = duration.hours();
  const seconds = duration.seconds();
  const milliseconds = duration.milliseconds();

  const yearsText = getDurationTextOrDefault(years, "Year");
  const monthsText = getDurationTextOrDefault(months, "Month");
  const weeksText = getDurationTextOrDefault(weeks, "Week");
  const daysText = getDurationTextOrDefault(days, "Day");
  const hoursText = getDurationTextOrDefault(hours, "Hour");
  const secondsText = getDurationTextOrDefault(seconds, "Second");
  const millisecondsText = getDurationTextOrDefault(
    milliseconds,
    "Millisecond"
  );

  return `${yearsText}${monthsText}${weeksText}${daysText}${hoursText}${secondsText}${millisecondsText}`;
}

function getDurationTextOrDefault(duration, unit) {
  if (duration <= 0) return "";
  unit = duration === 1 ? unit : unit + "s";
  return `${duration} ${unit} `;
}

const start = new Date("2020-01-07T20:24:00.000Z");
const end = new Date();

document.getElementById("app").innerHTML = `
<h1>Duration</h1>
<div>
  ${getDurationText(start, end)}
</div>
`;

Did the output meet your expectations?

UPDATE Deducted weeks from days manually due to moment's lack of automatic handling.

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

Exploring the NextPage type in Next.js

Could someone provide an explanation of the NextPage type within a Next.js TypeScript project? Most sources mention that it is used for type assignment in Next.js, but I am curious about its practical purpose. When and why should we utilize this type? Wha ...

Sort the ngFor Angular loop by the start_date

Within the select available date section, there is an array of dates like the one shown in the image . The following code uses ngFor: <div *ngFor="let date of tripdetail.trip_availabledate; let i = index;"> <a [ngClass]="{'active': ...

Tips for creating image hover effects on jcarousel

I have successfully implemented Jcarousel from and it's functioning perfectly. Is there a way to create a rollover effect for the images when hovering over them with the mouse? What JavaScript code should be used for this, and where should it be impl ...

Customize the CSS for the column containers in Material-UI's DataGrid with the

I am facing a challenge in trying to override the CSS property position on the .MuiDataGrid-columnsContainer. Upon reviewing the information available on https://material-ui.com/api/data-grid/#css, it seems that there is a rule defined for root but not spe ...

Ways to guarantee that the factory promise is fulfilled prior to the execution of the

So far, I have always found valuable help by studying existing answers on stackoverflow, but now I've hit a roadblock. I'm currently working on an app that utilizes a directive to generate calendar month boxes. <app2directive class="column_5 ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Tips on reducing the number of "$routeProvider.when" statements in a complex application

Is there a more efficient way to handle routing in AngularJS, specifically for loading html templates based on $location.path? My current approach involves a long list of "Whens" that will become unmanageable as my application grows. .config(['$rout ...

The Vue component's TypeScript object prop type does not match the expected value

Having trouble with the type of Object properties in Vue Single File Components using TypeScript (created with Vue CLI 3)? Check out the example below to see the issue. The type of this.product is currently showing as (() => any) | ComputedOptions<a ...

After completing the Spotify authentication process using implicit grant in a React application, the redirection is not functioning as

I am working on integrating Spotify authentication using the implicit grant method as outlined in their documentation. I have implemented the relevant code into a React component and successfully logged into Spotify. However, I am facing an issue where the ...

Chess.js TypeScript declaration file for easy implementation

Currently, I am delving into learning typescript and have taken up the challenge of crafting a declaration file for the chess.js library. However, it seems that I am struggling to grasp the concept of creating one. Whenever I attempt to import the library ...

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

Customizing default attribute prop types of HTML input element in Typescript React

I am currently working on creating a customized "Input" component where I want to extend the default HTML input attributes (props). My goal is to override the default 'size' attribute by utilizing Typescript's Omit within my own interface d ...

Experience a seamless front/back DIV transition with a mouseover effect similar to the ones on USAT

Recently, I was tasked with creating a mouseover transition effect for a div similar to the one used on USAToday's website. The structure of the boxes on the site includes: <div class="asset"> <div class="front">'image and some t ...

The error message "Attempting to send a message using an undefined 'send' property in the welcomeChannel" is displayed

bot.on('guildMemberAdd', (member) => { console.log(member) const welcomeChannel = member.guild.channels.cache.find(channel => channel.name === 'welcome'); //const channelId = '789052445485563935' // welcome c ...

When items are removed client-side, the Listbox becomes null

Given a Web Forms project inherited by me, I am relatively new to the field of Web development. The page in question features 2 listboxes: lstCaseLoad, containing "Caseloads" (ID numbers), and lstAssignedCaseLoad, filled with Caseloads chosen by the Form U ...

Modify button behavior on click after the initial press

Struggling to make this work the way I want. I have a button that should execute Javascript function A when clicked, and in function A, I need to change the onclick attribute to function B. This way, on the second tap of the button, it will trigger functio ...

Tips for effectively utilizing the Ngrx navigation function

While exploring NgRx, I stumbled upon navigation. According to the documentation, it seems like this effect should trigger when the component loads. However, I'm facing an issue where this effect is not getting triggered. Other effects that I've ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Exploring Vue.prototype attributes and utilizing them

I'm facing a challenge while attempting to globally set a property using Vue.prototype. This is what I currently have: microsoftTeams.initialize(); microsoftTeams.getContext((context) => { Vue.prototype.$teamsContext = true; }); new Vue({ ...

I am experimenting with an express middleware that can either return next() or next("route")

After developing a middleware function that returns next() if a route's parameters are defined by queryItems, I came across a useful tool called node-mocks-http. However, it does not fake the next object. This led me to explore how this can be achieve ...