私はJavaScriptで日年の数ヶ月の時間を計算しようとしていますです計算Perod日から、日付には、入力
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のように渡されたとき:3- Apr-2017とdate2:201-Apr-2017 27日を返しますが、実際には4月3日から30日までの28日間です。
年、月、日の正確な日数を計算するためのアイデアは、すでに2日間費やしています。
'28日4月3日〜27日?私はフォローしていません。 – Dom
4月3日から30日までの28日間、私の悪いことを申し訳ありません。私は自分の質問を編集する方法を知らない。 –
あなたがしなければならないことは、入力を 'Date'オブジェクトに構文解析することだけです。 'Date'はタイムスタンプで表されるので、算術演算(+、 - 、*、/、%)が可能です。ここに参照があります:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Dateあなたが 'Date'として適切な期間を得たとき、あなたは月、年などを得ることができます'dateObj.getFullYear()'、 'dateObj.getMonth()'など – Aloso