Reputation: 17
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
Upvotes: 1
Views: 94
Reputation: 30685
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; }
Upvotes: 2
Reputation: 290
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")
Upvotes: 2