Home > OS >  How can i convert string to only days?
How can i convert string to only days?

Time:11-30

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

CodePudding user response:

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")
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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 ) ${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; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related