我正在尝试用 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/