Tips for creating a consistent format based on test cases

  var years = Math.floor(seconds / (3600*24*365))
  seconds -= years*3600*24*365
  var days = Math.floor(seconds / (3600*24))
  seconds  -= days*3600*24
  var hrs   = Math.floor(seconds / 3600)
  seconds  -= hrs*3600
  var minutes = Math.floor(seconds / 60)
  seconds  -= minutes*60

console.log(formatDuration(3662)); // 1 hour, 1 minute and 2 second
console.log(formatDuration(62)); // 1 minute and 2 second
console.log(formatDuration(94608000)); // 3 years

How to log the duration in the specified format? Thank you for your help.

If there is only one entity, no comma, no "and".

If there are two entities, use "and".

If there are three entities, use commas and "and".

Answer №1

While it may be a bit lengthy to do manually, formatting durations can definitely be achieved with the following code snippet:

function formatDuration(seconds) {
    let years = Math.floor(seconds / (3600 * 24 * 365));
    seconds -= years * 3600 * 24 * 365;
    let days = Math.floor(seconds / (3600 * 24));
    seconds -= days * 3600 * 24;
    let hrs = Math.floor(seconds / 3600);
    seconds -= hrs * 3600;
    let minutes = Math.floor(seconds / 60);
    seconds -= minutes * 60;
    let result = '';
    
    // Code continued...

If you prefer a more efficient solution, I recommend exploring a time library like Moment.js, which is highly regarded in this field.

Answer №2

After analyzing the provided code on the given three examples, it has been confirmed that everything is functioning correctly. The code even validates the presence of the ending s.


function convertTimeToReadableFormat(seconds){
  var years = Math.floor(seconds / (3600*24*365))
  seconds -= years*3600*24*365
  var days = Math.floor(seconds / (3600*24))
  seconds  -= days*3600*24
  var hours   = Math.floor(seconds / 3600)
  seconds  -= hours*3600
  var minutes = Math.floor(seconds / 60)
  seconds  -= minutes*60
  let timeObj = {};
  
  //Include values only if they are greater than or equal to 1
  if(years >= 1) timeObj.years = years;
  if(days >= 1) timeObj.days = days;
  if(hours >= 1) timeObj.hours = hours;
  if(minutes >= 1) timeObj.minutes = minutes;
  if(seconds >= 1) timeObj.seconds = seconds;
  
  //Get keys of timeObj
  let objKeys = Object.keys(timeObj); 
  let timeString = ''; //The final formatted string to be returned
  
  for(let j = 0; j < objKeys.length; j++){
      let currentKey = objKeys[j];
      let value = timeObj[currentKey];
      
      //Remove 's' at the end if the value is singular
      currentKey = (value > 1) ? currentKey : currentKey.substring(0, currentKey.length - 1);
      
      //Add 'and' before the last value
      if(j === objKeys.length - 1 && objKeys.length != 1) timeString += ' and ';
      else timeString += ',' //Add a comma for all values except the last one
      
      timeString += `${value} ${currentKey}`;
  }
  
  return timeString.substring(1, timeString.length); // Remove the leading comma added in the loop above
}

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 transform these into five columns within a single row using the Material-UI Grid system?

I'm trying to align 5 columns in one row, but I'm struggling to achieve the desired layout. Here is what I currently have: https://i.stack.imgur.com/d3z3n.png Any tips on how to make all columns appear in a single row? You can also view my att ...

How to store data retrieved with $http.get in AngularJS into a variable

I am attempting to assign data retrieved from $http.get to a variable in my controller. $http.get(URL).success(function (data) { $scope.results = data; console.log('results within $http.get :'+ $scope.results); }); console.lo ...

The functionality of the slick slider seems to be malfunctioning

I've been trying to integrate the slick slider into my website, but it just won't work. I've double-checked everything multiple times, but I can't seem to find the issue. It's driving me crazy! If anyone can help me identify the pr ...

Transform JSON headers and rows into Object keys using Node.js

I am currently working on retrieving data from an API in JSON format using Node JS. The JSON data consists of headers and rows, including information such as "Vendor, Price, SKU, Error" (see the attached screenshot). I am looking to structure this data int ...

Utilize the UseQuery graphql function in conjunction with the useState hook within useEffect, allowing for the execution of an additional useEffect to update additional state

In my NextJS project, I am utilizing Apollo for graphQL queries and encountering an issue with the stateData.allProducts section. Despite setting the state in the useEffect and including data as a dependency in the array, the error claims it is null when d ...

Display a modal when a user is not authorized in vue-router

After stumbling upon this post on Medium, I decided to implement its concepts into my project. My goal was to verify a user's authorization to access a particular route, and if unauthorized, display a modal pop-up. In order to achieve this, I made s ...

Is Your CanvasJS Chart Traveling in Reverse?

My charts are displaying dates in reverse order, can anyone help me figure out what's causing this issue? I've checked the documentation but couldn't find anything that would explain this problem. Link to documentation: Here is a screensh ...

Ways to display a different landing page when navigating to the homepage of a website

In the Next application, I have set up a dynamic route at the root of my pages folder as src/pages/[page].js While this works smoothly for pages with slugs like example.com/my-page, it poses a challenge when trying to access a designated slug named homepa ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

What could possibly be causing the "Unexpected token (" error to appear in this code?

Sorry if this appears as a typo that I am struggling to identify. My browser (Chrome) is highlighting the following line <a class="carousel-link" onclick="function(){jQuery('#coffee-modal').modal('show');}">Book a coffee</a> ...

Load texture programmatically instead of using MTL files

I've successfully loaded an OBJ file and linked it with an MTL to provide a texture. However, I'm struggling to specify which texture should be associated with the model directly in the code; it seems that the texture only appears on the model if ...

Is there a way to raise an error in React Native and make it visible?

I am working on a functional component where I need to call a method from another .js file. The method in the external file intentionally throws an error for testing purposes, but I want to propagate this error up to the functional component's method. ...

Prevent secret select fields from being submitted within a form

In my interface, there are a couple of dropdowns where a user can select the first option and based on that selection, a new dropdown will appear. Currently, when posting the form, all the select dropdown values are included in the post data, even the hid ...

What is the method to create all possible combinations from the keys of a JSON object?

How can I generate object B that includes all combinations of object A using a key-value pair? { "x": "data-x", "y": "data-y", "z": "data-z" } The desired output should look like this: { ...

Using the method window.open() will launch a new window instead of opening a new tab

When the page loads, I am using JavaScript to call window.open. window.open(url, "Test Page"); Initially, it opens a new Chrome window and displays the page. However, when I use the same JavaScript code after the page has loaded, it opens the page in a n ...

Unable to Achieve Full Height with Vuetify Container

Challenge: I'm facing an issue with my <v-container> component not consistently spanning the entire height of the application. Despite trying various methods such as using the fill-height property, setting height: 100%;, height: 100vh;, and expe ...

The presence of Firefox Marionette has been identified by hCaptcha

Whenever I go on indeed.com using the firefox web driver in Marionette mode, I keep encountering an hCaptcha popup. In an attempt to avoid this, I experimented with a user script that alters the navigator.webdriver getter to return false right at the sta ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

Is Python being used to track NBA.com stats?

Does anyone have any advice on how to extract NBA.com "tracking" stats using a python script and display them in a simple table? I'm particularly struggling with this specific section of stats on the site. Accessing stats directly from NBA.com can be ...

HTML is not connecting to CSS

I'm having trouble linking my external CSS to my HTML file. In the head of my index.html, I have this code: <head> <title>Twenty by HTML5 UP</title> <meta charset="utf-8" /> <meta name="viewport ...