我想在年月日在JavaScript计算时间计算Perod在年月日在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
}
的问题是,当日期已过像DATE1:3- 2017年4月和2日:2017年4月30日。它返回27天,但事实上这些是从4月3日到30日28天。
任何想法来计算准确的日子在年,月和日,我已经花了两天。
'28天“4月3日至27日”?我没有跟随。 – Dom
4月3日至30日28天为我的坏事感到遗憾。我不知道如何编辑我的问题。 –
您只需将输入解析到“Date”对象中即可。由于Date由时间戳表示,它允许算术运算(+, - ,*,/,%)。以下是参考资料:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date,当您获得“日期”的适当期限时,您可以获得几个月,几年等'dateObj.getFullYear()','dateObj.getMonth()'等 – Aloso