Home > Software engineering >  how to turn a string time into number of seconds in javascript language
how to turn a string time into number of seconds in javascript language

Time:11-24

how can i turn a string time into number of seconds for example a javascript function to_number_of_seconds like this.

let a = '1h';
let b = '3d';
let a = to_number_of_seconds(a);
let b = to_number_of_seconds(b);

and i get a=3600 and b=259200

Thanks in advance.

CodePudding user response:

Here is a simple script using regex and destruct

const h = 60*60;
const d = 24*h;
const secs = {"h":h,"d":d};
const stringToSeconds = str => {
  const [_,num,unit] = str.match(/(\d )(\w)/);
  return num * secs[unit];
};

let a = '1h';
let b = '3d';

let secs1 = stringToSeconds(a);
let secs2 = stringToSeconds(b);

console.log(secs1,secs2)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Here is another method that can be used for most of the time formats :

const s = 1, m = 60 * s, h = 60 * m, d = 24 * m;
const timeElementsJson = { s, m, h, d };


const to_number_of_seconds = (timeString = "1d:2h:35m:25s") => {

    const TimeElements = timeString.split(":");
    return TimeElements.map((timeElement) => {
        return timeElementsJson[timeElement.slice(-1)] *  timeElement.slice(0, -1)
    }).reduce((a, b) => a   b, 0);
}

let a = '1h';
let b = '3d';
let a = to_number_of_seconds(a);
let b = to_number_of_seconds(b);

This can be used for strings like 'h', 'd', 'm', 's' and can also be modified for 'y', 'M', 'w', and combination of them as declared in the input parameter (try just calling the function with empty input values).

  • Related