Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
how to turn a string time into number of seconds in javascript language

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 * h;
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).

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!