質問
方法を教えてください、との差の二日時()オブジェクトではJavaScriptを返却のみの数ヶ月で、本当は違いがあると思います。
当らせる可能性もあります:)
解決
「違いの月数」の定義は、解釈の多くの対象となります。 : - )
あなたは、JavaScriptのDateオブジェクトから月の年、月、日を取得することができます。あなたが探しているものの情報に応じて、2つの時点の間でどのように何ヶ月把握するために、それらを使用することができます。
たとえば、既製カフ、この発見どのように多くの2つの日付の間ののフルヶ月の嘘、部分的ヶ月数えていない(例えば、それぞれの日付が入っている月を除く)アウト>function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 15: December 2008, all of 2009, and Jan & Feb 2010
monthDiff(
new Date(2010, 0, 1), // January 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 1: February 2010 is the only full month between them
monthDiff(
new Date(2010, 1, 1), // February 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 0: There are no *full* months between them
(JavaScriptで月の値が0 = 1月で始まることに注意してください。)
典型的な2月3日は8月(〜9.677パーセント)で3日以上、その月の大きな部分(〜10.714パーセント)で、そしてもちろんのも、2月ので、上記のわずか数ヶ月を含めるは、はるかに複雑になっています閏年かどうかに応じて、移動するターゲットます。
他のヒント
あなたは月の日付を考慮していない場合は、これははるかに簡単な解決策である。
function monthDiff(dateFrom, dateTo) {
return dateTo.getMonth() - dateFrom.getMonth() +
(12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}
//examples
console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1
月のインデックスは0ベースであることに注意してください。この手段そのJanuary = 0
とDecember = 11
ます。
時々、あなたは完全に日の部分を無視して2つの日付の間の数ヶ月だけの量を取得することができます。あなたが持っていたのであれば、たとえば、2 dates- 2013年6月21日から2013年/ 10/18 - とあなただけ2013/06および10分の2013部品気に、ここでのシナリオと可能な解決策があります:
var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
month1++;
month2++;
}
var numberOfMonths;
1.IfあなたはMONTH1とMONTH2
の両方を除いた2つの日付の間の数ヶ月だけの数をしたいですnumberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;
2.Ifはあなたがいずれかのヶ月の含める
numberOfMonths = (year2 - year1) * 12 + (month2 - month1);
3.Ifはあなたが数ヶ月の両方を含める
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
ここでは正確に2つの日付の間の月数を提供することを機能があります。
デフォルトの動作では、例えば、全体の数ヶ月をカウント3ヶ月と1日には、3ヶ月の違いになります。 3ヶ月と1日の差が4ヶ月として返されるようにするには、roundUpFractionalMonths
としてtrue
のPARAMを設定することでこれを防ぐことができます。
の(T.J。クラウダーの答え)上記の受け入れ答えは、それが時々間違った値を返し、正確ではありません。の
明らかに間違っているたとえば、monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015'))
を返します0
。正しいの違いは、1月全体または2ヶ月のいずれかを切り上げされます。
ここで私が書いた機能があります:
function getMonthsBetween(date1,date2,roundUpFractionalMonths)
{
//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 startDate=date1;
var endDate=date2;
var inverse=false;
if(date1>date2)
{
startDate=date2;
endDate=date1;
inverse=true;
}
//Calculate the differences between the start and end dates
var yearsDifference=endDate.getFullYear()-startDate.getFullYear();
var monthsDifference=endDate.getMonth()-startDate.getMonth();
var daysDifference=endDate.getDate()-startDate.getDate();
var monthCorrection=0;
//If roundUpFractionalMonths is true, check if an extra month needs to be added from rounding up.
//The difference is done by ceiling (round up), e.g. 3 months and 1 day will be 4 months.
if(roundUpFractionalMonths===true && daysDifference>0)
{
monthCorrection=1;
}
//If the day difference between the 2 months is negative, the last month is not a whole month.
else if(roundUpFractionalMonths!==true && daysDifference<0)
{
monthCorrection=-1;
}
return (inverse?-1:1)*(yearsDifference*12+monthsDifference+monthCorrection);
};
が必要な場合は数ヶ月間フルにかかわらず、月が28日、29、30、31日です。下記すべきます。
var months = to.getMonth() - from.getMonth()
+ (12 * (to.getFullYear() - from.getFullYear()));
if(to.getDate() < from.getDate()){
months--;
}
return months;
この拡張版ではその答え https://stackoverflow.com/a/4312956/1987208 が修正の場合で計算すると1ヶ月の場合から31日の1日(1日).
これは、次のとおりです;
- 1月31日までJan--->30日--->結果0(論理的でないアルファ)
- 1月1Mar--->28日29日前--->結果1の(論理的で完全な月)
- 15Feb15Mar--->28日29日前--->結果1(論理から一ヶ月経過)
- 31Jan1Feb--->1日目--->結果0(かに記載の回答の結果(1月)
JavaScriptで2つの日付の間の月の差ます:
start_date = new Date(year, month, day); //Create start date object by passing appropiate argument
end_date = new Date(new Date(year, month, day)
START_DATEとend_dateの間の総ヶ月ます:
total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())
私はこれは本当に遅れている知っているが、念のためにとにかくそれを投稿し、それは他の人に役立ちます。ここでは、2つの日付の間の数ヶ月の違いを数えるの良い仕事をしているようだ、私が思いついた関数です。それは確かにMr.Crowderのより多大のraunchierですが、日付オブジェクトを介してステッピングすることで、より正確な結果を提供します。これは、AS3であるが、あなただけの強い型付けをドロップすることができるはずです、あなたはJSがあるでしょう。そこに誰も外を見てよりよいそれを作るためにお気軽に!
function countMonths ( startDate:Date, endDate:Date ):int
{
var stepDate:Date = new Date;
stepDate.time = startDate.time;
var monthCount:int;
while( stepDate.time <= endDate.time ) {
stepDate.month += 1;
monthCount += 1;
}
if ( stepDate != endDate ) {
monthCount -= 1;
}
return monthCount;
}
違いを見つけるために、減算、その後、数ヶ月の面でそれぞれの日付を考えてみます。
var past_date = new Date('11/1/2014');
var current_date = new Date();
var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());
これは日を無視して、あなたに2つの日付の間の数ヶ月の違いを取得します。
D2の日付がより大きくなるか、D1のと等しいかどうかをチェックできるだけではなく、完全な暦月よりも、T.J.の答え@上で展開します。 d1はその月で、その後、1以上の月が存在しているよりも、d2が、後でその月であればそれは、あります。あなただけのこれを行うことができる必要がありますのでます:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
// edit: increment months if d2 comes later in its month than d1 in its month
if (d2.getDate() >= d1.getDate())
months++
// end edit
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10
これは完全に時間の問題(午後3時午後4時と4月3日で、例えば3月3日)を考慮していませんが、それは、より正確で、コードだけのカップルラインのためだ。
ある二つのアプローチの数の一連のセッティングも対象に伴い、カレンダー、または反復&遅いものの、取り扱うすべての奇妙少なくとも取扱いても試験します。
場合は繰り返し処理を実行し、カレンダー、incrementingの開始日から一月に見た場合の末日です。この代表者の異常-取り扱いに日()授業ができ の場合 やっているこの大きます。ジェームズの答えはこのアプローチ.も同じくらい嫌いになっているのでしょうけど、子供たちの何割かは、この"安全な"アプローチ、といっ 一つ 計算の性能差が無視できる。したがってみを最適なタスクを実行されます。
現在、 の場合 ま算定この機能は、データセットにおいていないのかもしれません走らせたいという機能する各列(または神を禁じ、複数回実績)。その場合は、利用できるほとんどその他の回答はこちら を除く の受け入れに答えるだけ間違った( new Date()
や new Date()
は-1)?
こちらも刺し、数学的、迅速にアプローチを占める異なる月の長さ、うるう年です。まるべき機能を使用するようにすればすることが、データセット(この計算&ー)となります。ばかりのときに必要なので、一度使用-ジェームスの反復型アプローチとしてい取扱いを委託すべての(多くの)の例外日()オブジェクトです。
function diffInMonths(from, to){
var months = to.getMonth() - from.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));
if(to.getDate() < from.getDate()){
var newFrom = new Date(to.getFullYear(),to.getMonth(),from.getDate());
if (to < newFrom && to.getMonth() == newFrom.getMonth() && to.getYear() %4 != 0){
months--;
}
}
return months;
}
ここであなたは少ないループに他のアプローチを行ってます:
calculateTotalMonthsDifference = function(firstDate, secondDate) {
var fm = firstDate.getMonth();
var fy = firstDate.getFullYear();
var sm = secondDate.getMonth();
var sy = secondDate.getFullYear();
var months = Math.abs(((fy - sy) * 12) + fm - sm);
var firstBefore = firstDate > secondDate;
firstDate.setFullYear(sy);
firstDate.setMonth(sm);
firstBefore ? firstDate < secondDate ? months-- : "" : secondDate < firstDate ? months-- : "";
return months;
}
計算の違いをコミックを含む画分の月(日)。
var difference = (date2.getDate() - date1.getDate()) / 30 +
date2.getMonth() - date1.getMonth() +
(12 * (date2.getFullYear() - date1.getFullYear()));
例えば:
date1:24/09/2015(月24日-2015年度)
date2:09/11/2015(9月-2015年)
の違い:2.5(月)
これは罰金を動作するはずます:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months += d2.getMonth() - d1.getMonth();
return months;
}
できるこのソリューションは、この function
を返します月の違いの整数又は番号
過 開始日 としての最初または最後の param
, は、耐故障.意味の機能も同じ値を戻す.
const diffInMonths = (end, start) => {
var timeDiff = Math.abs(end.getTime() - start.getTime());
return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}
const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));
// shows month difference as integer/number
console.log(result);
function calcualteMonthYr(){
var fromDate =new Date($('#txtDurationFrom2').val()); //date picker (text fields)
var toDate = new Date($('#txtDurationTo2').val());
var months=0;
months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
months -= fromDate.getMonth();
months += toDate.getMonth();
if (toDate.getDate() < fromDate.getDate()){
months--;
}
$('#txtTimePeriod2').val(months);
}
コードを返します後だけでなくとして考慮に入れ部分カ月の日数のNRを取ることによって、2つの日付の間の完全なヶ月ます。
var monthDiff = function(d1, d2) {
if( d2 < d1 ) {
var dTmp = d2;
d2 = d1;
d1 = dTmp;
}
var months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
if( d1.getDate() <= d2.getDate() ) months += 1;
return months;
}
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1
monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0
monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0
function monthDiff(d1, d2) {
var months, d1day, d2day, d1new, d2new, diffdate,d2month,d2year,d1maxday,d2maxday;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
months = (months <= 0 ? 0 : months);
d1day = d1.getDate();
d2day = d2.getDate();
if(d1day > d2day)
{
d2month = d2.getMonth();
d2year = d2.getFullYear();
d1new = new Date(d2year, d2month-1, d1day,0,0,0,0);
var timeDiff = Math.abs(d2.getTime() - d1new.getTime());
diffdate = Math.abs(Math.ceil(timeDiff / (1000 * 3600 * 24)));
d1new = new Date(d2year, d2month, 1,0,0,0,0);
d1new.setDate(d1new.getDate()-1);
d1maxday = d1new.getDate();
months += diffdate / d1maxday;
}
else
{
if(!(d1.getMonth() == d2.getMonth() && d1.getFullYear() == d2.getFullYear()))
{
months += 1;
}
diffdate = d2day - d1day + 1;
d2month = d2.getMonth();
d2year = d2.getFullYear();
d2new = new Date(d2year, d2month + 1, 1, 0, 0, 0, 0);
d2new.setDate(d2new.getDate()-1);
d2maxday = d2new.getDate();
months += diffdate / d2maxday;
}
return months;
}
ロジック以下ヶ月で違いをフェッチします。
(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())
function monthDiff(date1, date2, countDays) {
countDays = (typeof countDays !== 'undefined') ? countDays : false;
if (!date1 || !date2) {
return 0;
}
let bigDate = date1;
let smallDate = date2;
if (date1 < date2) {
bigDate = date2;
smallDate = date1;
}
let monthsCount = (bigDate.getFullYear() - smallDate.getFullYear()) * 12 + (bigDate.getMonth() - smallDate.getMonth());
if (countDays && bigDate.getDate() < smallDate.getDate()) {
--monthsCount;
}
return monthsCount;
}
私が使用しているものを参照してください:
function monthDiff() {
var startdate = Date.parseExact($("#startingDate").val(), "dd/MM/yyyy");
var enddate = Date.parseExact($("#endingDate").val(), "dd/MM/yyyy");
var months = 0;
while (startdate < enddate) {
if (startdate.getMonth() === 1 && startdate.getDate() === 28) {
months++;
startdate.addMonths(1);
startdate.addDays(2);
} else {
months++;
startdate.addMonths(1);
}
}
return months;
}
また、日をカウントし、数ヶ月でそれらを変換します。
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12; //calculates months between two years
months -= d1.getMonth() + 1;
months += d2.getMonth(); //calculates number of complete months between two months
day1 = 30-d1.getDate();
day2 = day1 + d2.getDate();
months += parseInt(day2/30); //calculates no of complete months lie between two dates
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2017, 8, 8), // Aug 8th, 2017 (d1)
new Date(2017, 12, 12) // Dec 12th, 2017 (d2)
);
//return value will be 4 months
の繁栄のために、の
Moment.js のではあなたが行うことでこれを実現することができます:
const monthsLeft = moment(endDate).diff(moment(startDate), 'month');
anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));
は一つのアプローチは、ジョダライブラリを使用して、簡単なJava Webサービス(REST / JSON)
を書くことであろうhttp://joda-time.sourceforge.net/faq.html#datediff
JavaScriptから2つの日付と呼び、そのサービスとの計算違いを
これはあなたのバックエンドがJavaであると仮定します。