【问题标题】:How can i convert string to only days?我怎样才能将字符串转换为只有天?
【发布时间】:2021-11-30 07:07:48
【问题描述】:

如何在 Javascript 中将“X 年 Y 月 Z 天”字符串转换为只有天数? 例如:

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

我必须拿832

【问题讨论】:

  • 欢迎来到 SO。我们要求编码人员就他们尝试过但遇到问题的代码提出问题。请将您尝试过的代码添加为minimal reproducible example

标签: javascript jquery string days


【解决方案1】:

您可以使用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; }

【讨论】:

    【解决方案2】:

    你可以拆分字符串并转换

    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")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2016-05-01
      • 2021-01-23
      • 1970-01-01
      • 2022-10-14
      相关资源
      最近更新 更多