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

261
Views
How can i convert string to only days?

how can I "X years Y months Z days" string convert to only days in Javascript ? ex:

var d="2 years 3 months 12 days";

and I must take 832

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

0

You can Split the string and convert

const date_str = "2 years 3 months 12 days"
const splitted_str=date_str.split(" ")
const years = parseInt(splitted_str[0])
const months = parseInt(splitted_str[2])
const days = parseInt(splitted_str[4])
const total_days=years*365+months*30+days
console.log(total_days+" days")

about 4 years ago · Juan Pablo Isaza Report

0

You can use RegExp.exec(), along with Array.reduce() to give you the desired output.

We define the intervals we consider along with their names and weights, then use .reduce() to sum the total days in the string.

function getTotalDays(str) {
    let intervals = [ { name: 'year', weight: 365 }, { name: 'month', weight: 30 }, { name: 'day', weight: 1 }];
    return intervals.reduce((acc, { name, weight}) => { 
        let res = new RegExp(`(\\d+)\\s${name}[\\s]?`).exec(str);
        return acc + (res ? res[1] * weight  : 0);
    }, 0);
}

console.log(getTotalDays("2 years 3 months 12 days"))
console.log(getTotalDays("6 months 20 days"))
console.log(getTotalDays("1 year 78 days"))
    
.as-console-wrapper { max-height: 100% !important; top: 0; }

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!