如何將“X 年 Y 月 Z 天”字串轉換為僅在 Javascript 中的天數?前任:
var d="2 years 3 months 12 days";
我必須拿 832
uj5u.com熱心網友回復:
您可以使用RegExp.exec()以及Array.reduce()來為您提供所需的輸出。
我們定義我們考慮的間隔以及它們的名稱和權重,然后使用 .reduce() 來總結字串中的總天數。
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; }
uj5u.com熱心網友回復:
您可以拆分字串并轉換
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370915.html
標籤:javascript 查询 细绳 天
下一篇:在充滿字串的串列中查找“n”
