Home > database >  Convert duration like "4d 5hours 8mins" to seconds
Convert duration like "4d 5hours 8mins" to seconds

Time:12-20

I'm not sure how I would do something like this.

For example, you input 4d 5hours 8mins and in return would result with 364080.

The input could have many possible combos like "4 days" or "4days" instead of "4d" etc.

I haven't tried anything. I am new to JS and searched for the answers but haven't found any that work for me.

CodePudding user response:

To convert a string input like "4d 5h 8m" into a total number of minutes, you can use the following steps:

Split the input string into an array of individual words using the split() function. For example:

const input = "4d 5h 8m";
const words = input.split(" "); // ["4d", "5h", "8m"]

Iterate over the array of words and parse the value and unit of each word. You can use a regular expression to extract the value and unit from each word. For example:

let totalMinutes = 0;

for (const word of words) {
     const value = parseInt(word.match(/\d /));
     const unit = word.match(/[a-zA-Z] /);
  if (unit === "d") {
    totalMinutes  = value * 1440; // 1440 minutes in a day
  } else if (unit === "h") {
     totalMinutes  = value * 60; // 60 minutes in an hour
   } else if (unit === "m") {
   totalMinutes  = value;
 }
}

CodePudding user response:

You can do this in three steps:

  • .replace() -- remove space between amount and unit
  • .split() -- split on spaces
  • .reduce() -- reduce amount and unit to seconds

Working code with examples:

[
  '4days 5hours 8mins',
  '4days 5hours 8mins 20secs',
  '14 days 15 hours 18 mins',
  '4D 5 Hours 8M'
].forEach(str => {
  let time = str
    .replace(/(\d) *([a-z])[a-z]*/gi, '$1$2')  // remove space between amount and unit
    .split(/  /)  // split on space
    .reduce((sum, val) => { // reduce amount and unit to seconds
      let m = val.match(/^([^a-z] )(.*)/i);
      if(m) {
        let amount = Number(m[1]);
        let unit = m[2]?.toLowerCase();
        if(unit === 'd') {
          sum  = amount * 60 * 60 * 24;
        } else if(unit === 'h') {
          sum  = amount * 60 * 60;
        } else if(unit === 'm') {
          sum  = amount * 60;
        } else if(unit === 's') {
          sum  = amount;
        }
      }
      return sum;
    }, 0);
  console.log(str, ' ==> ' , time, ' seconds');
});

Output:

4days 5hours 8mins  ==>  364080  seconds
4days 5hours 8mins 20secs  ==>  364100  seconds
14 days 15 hours 18 mins  ==>  1264680  seconds
4D 5 Hours 8M  ==>  364080  seconds
  • Related