【问题标题】:Want to calculate years, month, days from multiple dates in js想从js中的多个日期计算年月日
【发布时间】:2021-08-15 15:40:18
【问题描述】:

我根据用户的工作经验输入了多个日期。 例如,用户有类似的体验

exp1 = 2015 年 2 月 1 日至 2016 年 2 月 1 日 exp2 = 2016 年 2 月 6 日至 2020 年 3 月 28 日

现在我想计算这两个日期的年、月和日。

如何在 js 中实现这一点。我尝试了一下,但做不到。

【问题讨论】:

  • 请向我们展示您的尝试

标签: javascript node.js angular11


【解决方案1】:

看看这个:

function dateCalculator(date1,date2) {
    const diff = Math.floor(date1.getTime() - date2.getTime());
    const day = 1000 * 60 * 60 * 24;

    const days = Math.floor(diff/day);
    const months = Math.floor(days/31);
    const years = Math.floor(months/12);

    const output = `Years: ${years}, Months: ${months}, Days: ${days}`;

    return output
    }

const firstDate = new Date();
const secondDate = new Date(2015, 2, 1);
const diff = dateCalculator(firstDate,secondDate)
console.log(diff)

但是,您提供的日期格式不适用于此方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    相关资源
    最近更新 更多