javascript - 输入从日期和截止日期时,在 JavaScript 中计算年月日期间

标签 javascript period

我正在尝试用 javascript 计算年月日的时间

function getMonthsBetween (date1, date2)
{
    'use strict';
    // Months will be calculated between start and end dates.
    // Make sure start date is less than end date.
    // But remember if the difference should be negative.
    var start_date = date1;
    var end_date = date2;
    var inverse = false;

    if (date1 > date2)
    {
        start_date = date2;
        end_date = date1;
        inverse = true;
    }

    end_date = new Date(end_date); //If you don't do this, the original date passed will be changed. Dates are mutable objects.

    end_date.setDate(end_date.getDate() + 1);

    // Calculate the differences between the start and end dates
    var yearsDifference = end_date.getFullYear() - start_date.getFullYear();
    var monthsDifference = end_date.getMonth() - start_date.getMonth();
    var daysDifference = end_date.getDate() - start_date.getDate();

    var interval_month = yearsDifference +'-'+ monthsDifference +'-'+ daysDifference; 
    return interval_month;// Add fractional month
}

问题是当日期被传递时,例如日期1:2017年4月3日和日期2:2017年4月30日。它返回 27 天,但实际上是 4 月 3 日到 30 日的 28 天。

有什么想法可以计算准确的年月日天数吗,我已经花了两天时间了。

最佳答案

请参阅此示例:

[https://jsfiddle.net/2ozuvn0L/2/]

在此示例中,您需要传递开始日期和结束日期。

getPeriod(新日期(2016, 3, 3), 新日期(2017, 3, 30))

答案: 第 1 年、第 0 个月、第 27 天

关于javascript - 输入从日期和截止日期时,在 JavaScript 中计算年月日期间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43190691/

相关文章:

windows - 如何在 HH :29:55 and HH:59:55 in a windows batch file 触发命令

c# - 如何更新 ASPNetCoreRateLimit lib 的重试后值?

c# - 与 System.Windows.Forms.Timer 的间隔不一致

javascript - 使用 KnockoutJS 初始化后更新引导日期选择器

javascript - 取消所有Javascript的setTimeouts和setIntervals

javascript - 修改现有的 JavaScript 类方法

Java - 设置期间

javascript - 通过ajax调用渲染rails fields_for

javascript - 调试 JavaScript 事件

python - 如何按自定义重叠周期对 pandas 数据框进行分组?